I am reading https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html
It says
In other words, any type
TisSyncif&T(an immutable reference toT) isSend, meaning the reference can be sent safely to another thread. Similar toSend, primitive types areSync
How to understand this? If primitive types are Sync, so integer such as i32 is Sync. Thus &i32 can be sent safely to another thread. But I don’t think so. A number variable has to be moved to a thread by reading the book (contradiction). I don’t think a number reference in main thread can be send to another thread.
>Solution :
You’re confusing the concept of thread-safety with the concept of lifetime.
You are correct in that a reference to a value owned by main() can’t be sent to a spawned thread:
// No-op function that statically proves we have an &i32.
fn opaque(_: &i32) {}
fn main() {
let x = 0i32;
std::thread::spawn(|| opaque(&x)); // E0373
}
This doesn’t fail because &x is not Send (it is), but because std::thread::spawn() requires that the closure is 'static, and it isn’t if it captures a reference to something that doesn’t have static lifetime. The compiler gives us this hint along with the error:
note: function requires argument type to outlive `'static`
We can prove this by obtaining a reference with static lifetime (&'static i32) and sending it to a thread, which does work:
fn opaque(_: &i32) {}
fn main() {
static X: i32 = 0;
std::thread::spawn(|| opaque(&X));
}