I know the rule &mut T : Send requiring T : Send; it is not enough.
Send &'a mut T also requires 'a : 'static, which requires T living in a static scope.
Seems only static variable satisfies this.
While the question is, if T is a static variable, then I can access it directly in the other thread, why need I send the mut ref to the thread?
Any T of not static but satisfying the requirement exists?
|
52 | let mut x: u64 = 0;
| ----- binding `x` declared here
53 | let ptr: &mut u64 = &mut x;
| ^^^^^^ borrowed value does not live long enough
54 |
55 | / std::thread::spawn(move || {
56 | | ptr;
57 | | });
| |______- argument requires that `x` is borrowed for `'static`
58 | }
| - `x` dropped here while still borrowed
The problem in that code is not that &mut u64 is not Send. But the compiler just told you that. The problem is that threads created using thread::spawn() must not borrow, because they might live forever potentially (thus, any non-static borrows have the potential of expiring and becoming dangling).
If you want to use thread::spawn(), you'll need to hand it owned data. If you need to mutate something from multiple threads, then the usual way to do this is wrap it into Arc<Mutex<_>>:
'static is not only satisfied by static variables but by all owned data. Any type that does not contain any references (shorter than 'static) satisfies 'static (see here).
I'm not sure what you mean by "does not mean much". In what sense? Surely the 'static lifetime as well as static items do have a meaning. What's your actual complaint?
If you are having trouble expressing yourself in reasonably good English, then please seek the help of someone who is a fluent speaker to translate your question.
Well yes, of course &'a T does not satisfy 'static if 'a is not the 'static lifetime.
The way I see it, your problem is as follows:
You want to call a function which has an interface that requires its input to satisfy 'static. You have a program that does not satisfy the interface, because it tries to pass &'a mut T (not 'static).
I'd say you have three options to go from here:
use idiomatic shared-state concurrency as shown by @H2CO3 (Arc<Mutex<T>)
use something that has a less restrictive interface (like thread::scope).
take a completely different approach to concurrency, like message passing
Okay, then I've misinterpreted your question, my bad.
Unfortunately I don't have a deeper/more meaningful answer than that it allows you to use it in contexts that require it to be Send, but does not require it to be 'static (like Scope::spawn, for example).