Sub topic 9
Unsafe traits, Send, and Sync
This chapter assumes you know safe Rust ownership and borrowing, basic traits and generics, and how to spawn threads with std::thread. It also assumes you have read the earlier chapters on raw pointers and safety contracts.
What makes a trait unsafe
A trait is unsafe when implementing it carries a promise the compiler cannot check. Other code, including safe code and other unsafe code, relies on that promise. If the promise is false, the result is undefined behavior.
Compare this with an unsafe function. An unsafe function puts the burden on the caller. An unsafe trait puts the burden on the implementer. You write unsafe impl to say, "I have checked this, and I accept responsibility."
The standard library has several unsafe traits. The two you will meet most often are Send and Sync.
Send and Sync
Both traits are marker traits. They have no methods. They tell the compiler how a type may be used across threads.
| Trait | Meaning | Example consequence |
|---|---|---|
| `Send` | Ownership of a value can move to another thread. | `thread::spawn` requires the closure to be `Send`. |
| `Sync` | A shared reference `&T` can be used from several threads. `T` is `Sync` exactly when `&T` is `Send`. | `Arc<T>` is only `Send` if `T` is `Send + Sync`. |
The compiler implements these traits automatically. A struct is Send if all its fields are Send. It is Sync if all its fields are Sync. This is why most of your types are thread-safe without any effort.
Raw pointers are the common exception. *mut T and *const T are neither Send nor Sync. The compiler takes the cautious route because it knows nothing about what the pointer refers to. Any struct holding a raw pointer loses both traits.
Opting in with unsafe impl
If you know your type is safe to send, you can say so yourself.
struct SendPtr(*mut u8);
// SAFETY: the pointer is only used by one thread at a time and points to
// memory that is valid on any thread.
unsafe impl Send for SendPtr {}
fn main() {
let mut byte = 1u8;
let p = SendPtr(&mut byte as *mut u8);
let handle = std::thread::spawn(move || {
let p = p;
// SAFETY: `byte` outlives the thread because we join below.
unsafe { *p.0 = 2 };
});
handle.join().unwrap();
println!("{byte}");
}Without the unsafe impl, thread::spawn would reject the closure. The line let p = p; makes the closure capture the whole SendPtr. Without it, edition 2021 closures capture only the field p.0, which is a bare raw pointer and is not Send.
The SAFETY comment is the important part. It states the specific facts that make the promise true. A comment such as "this is fine" tells a reviewer nothing.
Choosing Send and Sync correctly
The two traits answer different questions, so a type can have one without the other.
Cell<T>isSendbut notSync. Moving it to another thread is fine. Sharing it is not, becausesetmutates through&selfwith no synchronization.Rc<T>is neither. Its reference count is not atomic, so two threads cloning it at once would corrupt the count.MutexGuardisSyncbut notSend. Some platforms require that a lock be released on the thread that took it.
Common errors
- Implementing
SendorSyncto silence a compiler error. The error is usually correct. Fix the design first, for example withArc<Mutex<T>>. - Forgetting generics. If your wrapper holds a
T, writeunsafe impl<T: Send> Send for Wrapper<T> {}. Without the bound, you promise safety for everyT, including ones that are not safe. - Assuming
Syncis enough for mutation.Syncallows shared access only. Mutation through a shared reference still needs a lock or atomics.
Exercise
A struct Handle contains a *mut i32. You want to move it to another thread. What do you write, and what must you be able to justify?
Show answer
Write unsafe impl Send for Handle {}. You must justify, usually in a SAFETY comment, that the pointed-to memory stays valid for as long as the other thread uses it, and that no other thread accesses it at the same time without synchronization.
Exercise
Why is Rc<T> not Send, even when T is Send?
Show answer
Its reference count is a plain integer, not an atomic one. Clones on two threads could update it at the same time, which is a data race that corrupts the count.