These are chat archives for rust-lang/rust

16th
Sep 2015
John C F
@critiqjo
Sep 16 2015 13:50

Please tell me if my understanding is correct. I couldn't find any documentation explaining it.

  • Rust compiler is agnostic about the concept of "threads"; Types are marked with Send and Sync appropriately, and the compiler simply checks for compatibility of the closure object passed to the thread::spawn method.
  • When we define a lamda function move || local_var + 1, a closure object (say f) is generated by the compiler. If local_var (and all the objects wrapped) implements Send, f will be marked Send.
  • What I'm not clear about is Sync. How does Rust find out about "sharing"? Is Arc treated as a reference to the an object, as opposed to a first class object, by the compiler? How does it do that? How does it distinguish objects of type Arc<T> when T is RefCell<U> and not.

Right now, I'm looking at rust compiler as a magical program (it really is)!! Sorry for my laziness to browse the source code to find the answer.

Peter Atashian
@retep998
Sep 16 2015 13:53
The rust compiler is indeed agnostic with regards to threads. Everything is done through the Send/Sync marker traits
Arc<T> is Send and Sync only if T is also both Send and Sync
impl<T> Send for Arc<T> where T: Send + Sync + ?Sized
impl<T> Sync for Arc<T> where T: Send + Sync + ?Sized
@critiqjo Meanwhile RefCell<U> does not impl Sync, and so if you put it in an Arc<T> then that Arc will not be Send nor Sync
John C F
@critiqjo
Sep 16 2015 14:00
But usize, for example, is Send but not Sync right?...... Ahh... Immutability: "Sync if &T is thread safe"... So usize is Sync...
Right?
Peter Atashian
@retep998
Sep 16 2015 14:00
@critiqjo All types that do not use interior mutability are Sync
If a type does use interior mutability, then it is only Sync if that interior mutability is thread safe, aka it uses Mutex or RwLock or atomics
Since usize doesn't offer interior mutability it is automatically Sync
John C F
@critiqjo
Sep 16 2015 14:04
There is this line in documentation of Sync which confused me impl<T> Sync for Arc<T>, making no mention of T's traits... Thanks a lot...
Peter Atashian
@retep998
Sep 16 2015 14:05
The documentation should state that it depends on T being Send and Sync
actually there are 2 lines... one with and one without...
Peter Atashian
@retep998
Sep 16 2015 14:06
Yeah, that's just rustdoc being silly
One of them is for Arc from liballoc while the other is for Arc from libstd
std re-exporting types from other internal crates makes life difficult for rustdoc sometimes
John C F
@critiqjo
Sep 16 2015 14:11
:smile:
though why does it not show the same definition, a bug in rustdoc?
Peter Atashian
@retep998
Sep 16 2015 14:14
Yep
John C F
@critiqjo
Sep 16 2015 14:30
So Sync exists specifically due to Arc. If there was no Arc, there would be no need forSync (since there is no longer thread::scoped)...
Thanks again @retep998 ... You are a savior!!