Sub topic 9
Unsafe traits, Send, and Sync
This chapter assumes you know ownership, borrowing, traits and generics, and the earlier chapters of this tutorial on unsafe functions and safety contracts. Unsafe functions put a promise on the caller. Unsafe traits put a promise on the person who writes the impl. That promise matters most for Send and Sync, the two traits behind Rust's thread safety.
What an unsafe trait is
A trait is unsafe when implementing it can make other code, safe or unsafe, rely on a property the compiler cannot check. The implementor makes the promise, so you write unsafe impl.
/// Marker for types where a value made of all-zero bytes is valid.
///
/// # Safety
///
/// Implementors must guarantee that every byte of `Self` may be zero
/// and the result is a valid, initialized value. Types with references,
/// `NonZero*` integers, `Box`, or enums without a zero discriminant
/// must not implement this trait.
unsafe trait AllZeroValid: Sized {
fn zeroed() -> Self {
// SAFETY: the trait contract says all-zero bytes are a valid `Self`.
unsafe { std::mem::zeroed() }
}
}
// SAFETY: zero is a valid u32.
unsafe impl AllZeroValid for u32 {}
// SAFETY: an array of zero bytes is a valid [u8; 4].
unsafe impl AllZeroValid for [u8; 4] {}
fn main() {
let a = <u32 as AllZeroValid>::zeroed();
let b = <[u8; 4] as AllZeroValid>::zeroed();
println!("{a} {b:?}");
}The trait method zeroed is safe to call. Its body uses unsafe only because the trait contract guarantees the property. If someone wrote unsafe impl AllZeroValid for &u8 {}, every call to zeroed would produce a null reference, which is undefined behavior. The bug sits in the unsafe impl, not in the call site.
A trait should be unsafe when all three of these hold:
- Generic code will rely on a property of the implementing type.
- A wrong
implwould cause undefined behavior. - The compiler cannot check the property.
If a wrong impl only gives wrong answers, such as a bad Ord, a normal trait is enough. Unsafe code must not depend on safe traits being implemented correctly.
Where the unsafe goes
| Item | Who writes `unsafe` | What it means |
|---|---|---|
| `unsafe fn` | The caller | "I have met this function's preconditions." |
| `unsafe trait` declaration | The trait author | "Implementing this carries obligations." The author documents them under `# Safety`. |
| `unsafe impl` | The implementor | "I have checked that my type meets those obligations." |
| Safe method inside an unsafe trait | Nobody at the call site | The contract was already accepted at the `impl`. |
Send and Sync
Send and Sync are unsafe, automatically implemented marker traits. Their definitions:
T: Sendmeans a value of typeTcan be moved to another thread.T: Syncmeans a shared reference&Tcan be used from several threads at once. Equivalently,T: Syncexactly when&T: Send.
Both are auto traits. The compiler implements them for a struct or enum when all its fields implement them. You get thread safety by composition, and you never write impl Send for a plain struct.
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
fn main() {
assert_send::<Vec<i32>>();
assert_sync::<std::sync::Mutex<i32>>();
assert_send::<std::sync::Arc<std::sync::Mutex<i32>>>();
// Each of these lines fails to compile if you uncomment it:
// assert_send::<std::rc::Rc<i32>>(); // non-atomic refcount
// assert_sync::<std::cell::Cell<i32>>(); // unsynchronized interior mutability
// assert_send::<*mut u8>(); // raw pointers opt out
println!("all checked at compile time");
}Raw pointers are neither Send nor Sync. This is deliberate. Any struct holding a raw pointer loses both traits, and the compiler stops you from sharing it between threads by accident.
Why a manual impl is a real promise
The compiler's field-by-field rule is conservative. Sometimes a type is thread-safe for reasons the compiler cannot see, and that is when you write unsafe impl Send or unsafe impl Sync. You are claiming:
- For
Send: moving this value to another thread, and dropping it there, cannot cause a data race or break an invariant. A type holding a thread-local handle or an OS resource tied to one thread is notSend. - For
Sync: any number of threads can call&selfmethods at the same time without a data race.
The tutorial's raw-pointer example shows the first case:
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}");
}Two details matter here:
- The line
let p = p;makes the closure capture the wholeSendPtr. Since Rust 2021, closures capture individual fields, so usingp.0directly would capture the raw pointer, which is notSend. - The SAFETY comment names reasons that are true of this program. Phrases like "it should be fine" would not count as reasons.
Writing a Sync type: a spin lock
The classic reason to write unsafe impl Sync is a type that wraps UnsafeCell. UnsafeCell<T> is the only legal way to mutate through a shared reference, and it is !Sync. A lock type restores Sync by controlling access.
use std::cell::UnsafeCell;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
pub struct SpinLock<T> {
locked: AtomicBool,
value: UnsafeCell<T>,
}
// SAFETY: `value` is only reachable while `locked` is held, so at most one
// thread touches the `T` at a time. `T: Send` is required because
// `with_lock` lets any thread mutate (and so effectively take) the value.
unsafe impl<T: Send> Sync for SpinLock<T> {}
impl<T> SpinLock<T> {
pub const fn new(value: T) -> Self {
SpinLock {
locked: AtomicBool::new(false),
value: UnsafeCell::new(value),
}
}
pub fn with_lock<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
while self
.locked
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
std::hint::spin_loop();
}
// SAFETY: we hold the lock, so no other reference to the value exists.
let result = f(unsafe { &mut *self.value.get() });
self.locked.store(false, Ordering::Release);
result
}
}
static COUNTER: SpinLock<u32> = SpinLock::new(0);
fn main() {
let handles: Vec<_> = (0..4)
.map(|_| {
thread::spawn(|| {
for _ in 0..1000 {
COUNTER.with_lock(|n| *n += 1);
}
})
})
.collect();
for h in handles {
h.join().unwrap();
}
println!("{}", COUNTER.with_lock(|n| *n));
}This prints 4000. Three points about the design:
- The
Acquireon lock andReleaseon unlock make one thread's writes visible to the next thread that takes the lock. Without that ordering, mutual exclusion alone would not prevent a data race. - The bound
T: Sendon theimplis part of the proof.SpinLock<Rc<i32>>must not beSync, or two threads could each clone theRcand race on its count. - This lock is a teaching sketch. If
fpanics, the lock is never released and other threads spin forever. A real lock uses a guard type whoseDropreleases it.
Negative reasoning: when you must not implement
Use these questions before writing a manual Send or Sync impl:
- Does the type own its data, or does it point into memory owned elsewhere? If it points elsewhere, can that memory be freed or mutated while another thread uses the pointer?
- Does it use thread-local state, or an API that requires the same thread for creation and destruction? If so, it is not
Send. - Can
&selfmethods mutate anything without synchronization? If so, it is notSync. - Do the generic parameters need bounds? Wrapper types need
T: SendorT: Syncon the impl, as inSpinLock.
You can also opt out. Adding a PhantomData<*const ()> field makes your type !Send and !Sync on stable Rust. Use it when your type must stay on one thread for a reason the fields do not show.
Common errors
- Implementing
Syncwithout bounds on generics.unsafe impl<T> Sync for Wrapper<T> {}accepts anyT, includingRc<i32>. - Forgetting that
Dropruns on the receiving thread. ASendimpl must be sound for the destructor too. - Assuming
Syncmeans "can be mutated by many threads." It means&Tis safe to share. Mutation through&Tis safe only if the type itself synchronizes it, asMutexand atomics do. - Writing an unsafe trait with no
# Safetysection. Implementors then have nothing to check against.
Exercise
A type Handle holds a raw pointer to heap data that it owns exclusively, and it frees the data in Drop. All its methods that mutate take &mut self. The compiler reports that Handle is neither Send nor Sync. Which unsafe impl lines are justified, and what must you check first?
Show answer
Both can be justified, because an exclusively owned allocation behaves like a Box. unsafe impl Send for Handle {} is sound if the data does not depend on thread-local state and freeing it on another thread is allowed. unsafe impl Sync for Handle {} is sound because every mutating method needs &mut self, so &Handle only allows reads and cannot race. If the pointee type is generic, add bounds: T: Send for Send and T: Sync for Sync. Document each reason in a SAFETY comment.
Exercise
In the spin lock above, why is unsafe impl<T: Send> Sync for SpinLock<T> correct, while unsafe impl<T> Sync for SpinLock<T> would not be?
Show answer
with_lock gives any thread a &mut T, so threads effectively take turns owning the T. That is the same power as moving the T between threads, so T must be Send. Without the bound, SpinLock<Rc<i32>> would be Sync, and two threads could clone the Rc at the same time and race on its non-atomic reference count.
Exercise
What does the unsafe keyword on unsafe trait ask of the person who writes an impl, and why does the compiler enforce that they write unsafe impl?
Show answer
It asks them to check the trait's documented # Safety requirements and to promise that their type meets them. The compiler requires unsafe impl so the promise is visible in the source and shows up when reviewers search for unsafe. Other code, including safe code, may rely on the promise, so a false one can cause undefined behavior far from the impl.