Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to understand "primitive types are Sync" in rust?

I am reading https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html

It says

In other words, any type T is Sync if &T (an immutable reference to T) is Send, meaning the reference can be sent safely to another thread. Similar to Send, primitive types are Sync

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading