Sync in core::marker - Rust (original) (raw)
pub unsafe auto trait Sync { }
Expand description
Types for which it is safe to share references between threads.
This trait is automatically implemented when the compiler determines it’s appropriate.
The precise definition is: a type T
is Sync if and only if &T
isSend. In other words, if there is no possibility ofundefined behavior (including data races) when passing&T
references between threads.
As one would expect, primitive types like u8 and f64are all Sync, and so are simple aggregate types containing them, like tuples, structs and enums. More examples of basic Synctypes include “immutable” types like &T
, and those with simple inherited mutability, such as Box, Vec and most other collection types. (Generic parameters need to be Syncfor their container to be Sync.)
A somewhat surprising consequence of the definition is that &mut T
is Sync
(if T
is Sync
) even though it seems like that might provide unsynchronized mutation. The trick is that a mutable reference behind a shared reference (that is, & &mut T
) becomes read-only, as if it were a & &T
. Hence there is no risk of a data race.
A shorter overview of how Sync and Send relate to referencing:
&T
is Send if and only ifT
is Sync&mut T
is Send if and only ifT
is Send&T
and&mut T
are Sync if and only ifT
is Sync
Types that are not Sync
are those that have “interior mutability” in a non-thread-safe form, such as Celland RefCell. These types allow for mutation of their contents even through an immutable, shared reference. For example the set
method on Cell takes &self
, so it requires only a shared reference &Cell. The method performs no synchronization, thus Cell cannot be Sync
.
Another example of a non-Sync
type is the reference-counting pointer Rc. Given any reference &Rc, you can clone a new Rc, modifying the reference counts in a non-atomic way.
For cases when one does need thread-safe interior mutability, Rust provides atomic data types, as well as explicit locking viasync::Mutex and sync::RwLock. These types ensure that any mutation cannot cause data races, hence the types are Sync
. Likewise, sync::Arc provides a thread-safe analogue of Rc.
Any types with interior mutability must also use thecell::UnsafeCell wrapper around the value(s) which can be mutated through a shared reference. Failing to doing this isundefined behavior. For example, transmute-ing from &T
to &mut T
is invalid.
See the Nomicon for more details about Sync
.