What is the reasoning behind marking a type that contains !Send
fields (like Rc
or NonNull
) with the Send
trait? For instance, the standard library's LinkedList
works in this fashion: it contains Option<NonNull<_>>
fields and it implements Send
trait (when T
is Send
).
How is this safe, what are the guarantees and ways to work safely with such a type?
The raw pointer types are not Send because Rust cannot make any guarantees about the synchronization mechanisms that are in the underlying types, or when the pointers will be accessed. Rc is not Send because it uses a non-atomic reference counter which is not safe to send between threads.
Inheritance as a Type System and as Code SharingIf a language must have inheritance to be an object-oriented language, then Rust is not. There is no way to define a struct that inherits the parent struct's fields and method implementations.
Send means that a type is safe to move from one thread to another. If the same type also implements Copy , this also means that it is safe to copy from one thread to another. Sync means that a type is safe to reference from multiple threads at the same time.
Rust captures this through the Send and Sync traits. A type is Send if it is safe to send it to another thread. A type is Sync if it is safe to share between threads (T is Sync if and only if &T is Send).
Look at the rationale for NonNull
being !Send
:
NonNull
pointers are notSend
because the data they reference may be aliased.
But the NonNull
in LinkedList
is a private implementation detail. If this type knows that the inner type T
is Send
and the usage it does is also Send
-safe, (no unsafety in the public API) then it can reintroduce the Send
trait.
That guarantee basically winds down to ensuring that you cannot get mutable aliases to the inner types; and ensuring that there is no unexpected inner mutability (get a mutable reference from an immutable one).
These guarantees are not given by NonNull
but they are in LinkedList
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With