Sub topic 14
Writing unsafe impl Send and Sync correctly
This chapter assumes you know what Send and Sync promise, how auto traits derive them from fields, and why *mut T and Rc<T> opt out. You should also be comfortable with unsafe blocks, Drop, and Box::into_raw and Box::from_raw. Here you learn when a manual implementation is justified and how to write one that stays sound.
Why Send and Sync are unsafe traits
Send and Sync are declared as unsafe trait. Implementing one therefore needs the unsafe impl keywords. Unlike an unsafe block, which says "I checked that this operation is safe," unsafe impl says "I promise every user of this type may rely on this guarantee."
unsafe impl Send for X {}promises that moving anXto another thread cannot cause a data race or other undefined behavior.unsafe impl Sync for X {}promises that several threads can hold&Xat once without a data race. Equivalently,&XisSend.
The compiler does not check either promise. If you are wrong, safe code elsewhere in the program can trigger undefined behavior, and the fault lies with your unsafe impl.
When you need one
Most types never need a manual impl. The compiler derives both traits from the fields. You need an unsafe impl only when all of these hold:
- A field makes the compiler opt out. The usual cause is a raw pointer (
*const Tor*mut T), andNonNull<T>behaves the same way. - You have established that the type is in fact safe to move or share.
- No safe wrapper does the job. You could often use
Box<T>,Arc<Mutex<T>>, or an atomic and need no unsafe at all.
Check option 3 first. Typical legitimate cases are low-level containers, FFI handles, and custom synchronization primitives.
A correct implementation
This type owns a heap allocation through a raw pointer, just as Box<T> does.
use std::thread;
struct OwnedPtr<T> {
ptr: *mut T,
}
impl<T> OwnedPtr<T> {
fn new(value: T) -> Self {
OwnedPtr { ptr: Box::into_raw(Box::new(value)) }
}
fn get(&self) -> &T {
unsafe { &*self.ptr }
}
}
impl<T> Drop for OwnedPtr<T> {
fn drop(&mut self) {
unsafe { drop(Box::from_raw(self.ptr)); }
}
}
unsafe impl<T: Send> Send for OwnedPtr<T> {}
unsafe impl<T: Sync> Sync for OwnedPtr<T> {}
fn main() {
let p = OwnedPtr::new(String::from("hello"));
let handle = thread::spawn(move || p.get().len());
println!("{}", handle.join().unwrap());
}This program prints 5. The impls are sound because of three facts:
- Unique ownership. Nothing else aliases the allocation. Moving the
OwnedPtrmoves the only access path. - Drop runs on whichever thread owns the value. Dropping the inner
Ton another thread is only allowed ifT: Send. That is why the Send impl is bounded. - Shared access is read-only.
gethands out&T, so sharing&OwnedPtr<T>is the same as sharing&T. That is safe exactly whenT: Sync.
Always bound the type parameters
The most common mistake is to write the impl without bounds.
// Unsound: lets OwnedPtr<Rc<i32>> cross threads.
unsafe impl<T> Send for OwnedPtr<T> {}This compiles. It also allows OwnedPtr<Rc<i32>> to be sent to a thread. Two threads could then each hold clones of that Rc and update its non-atomic count at the same time. Safe code produced this data race, and only the incorrect unsafe impl allowed it.
The rule is to copy what the compiler would have derived and remove only the part you have justified. For a type that logically owns a T, require T: Send for Send and T: Sync for Sync. For a type that holds a *const T merely as a reference, mirror &T instead. In that case Send needs T: Sync, and Sync also needs T: Sync.
You can verify your bounds with the assertion helpers from earlier chapters. The following program compiles, and each commented line would be rejected if enabled.
use std::rc::Rc;
struct OwnedPtr<T> {
ptr: *mut T,
}
unsafe impl<T: Send> Send for OwnedPtr<T> {}
unsafe impl<T: Sync> Sync for OwnedPtr<T> {}
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
fn main() {
assert_send::<OwnedPtr<String>>();
assert_sync::<OwnedPtr<Vec<i32>>>();
// Each of these fails to compile, as it should:
// assert_send::<OwnedPtr<Rc<i32>>>();
// assert_sync::<OwnedPtr<std::cell::Cell<i32>>>();
}Keep checks like these in a unit test. They fail loudly if a later refactor changes a bound.
Implementing only one of the two
Send and Sync are independent promises, and a type can honestly provide only one. Cell<i32> is the standard example, because it can move between threads but cannot be shared. The following handle is Send but deliberately not Sync.
use std::thread;
struct Handle {
raw: *mut u32,
}
impl Handle {
fn new(value: u32) -> Self {
Handle { raw: Box::into_raw(Box::new(value)) }
}
// Writes without synchronization, so &Handle must never be shared.
fn bump(&self) {
unsafe { *self.raw += 1; }
}
fn value(&self) -> u32 {
unsafe { *self.raw }
}
}
impl Drop for Handle {
fn drop(&mut self) {
unsafe { drop(Box::from_raw(self.raw)); }
}
}
// One thread owns the Handle at a time, so moving it is fine.
unsafe impl Send for Handle {}
// No Sync impl: bump(&self) would race if two threads called it.
fn main() {
let handle = Handle::new(7);
let worker = thread::spawn(move || {
handle.bump();
handle.value()
});
println!("{}", worker.join().unwrap());
}The program prints 8. If you try to share &handle between two scoped threads, the compiler rejects it because Handle is not Sync. The missing impl is what stops the race.
What to check before you write the impl
Work through these questions for each field and each method.
| Question | If the answer is "yes" |
|---|---|
| Does the type uniquely own what the pointer targets? | `Send` is plausible, bounded by `T: Send` |
| Does anything alias the data, such as a clone, a global, or a callback registered elsewhere? | You must synchronize every access path, or skip the impl |
| Does a `&self` method mutate through the pointer? | `Sync` needs a lock or atomics around that mutation |
| Does the type touch thread-local state or an API tied to one thread (some GUI and FFI handles)? | Do not implement `Send` |
| Does `Drop` release a resource that must be released on the creating thread? | Do not implement `Send` |
| Does the type expose `&T` or `&mut T` for a generic `T`? | Bound the impl on `T: Send` or `T: Sync` as appropriate |
Common mistakes
- Unbounded generics. Covered above. If your type has a type parameter, a bare
unsafe impl<T> Sendis almost always wrong. - Implementing
SyncbecauseSendworked. Sending needs unique access, while sharing needs safe concurrent access. These are different conditions. - Forgetting the whole API. A new
&selfmethod that mutates through the raw pointer can invalidate aSyncimpl written earlier. The impl covers the entire public interface, so revisit it whenever you add a method. - Ignoring
Drop. The destructor runs on whichever thread owns the last value. If it is not safe off-thread, the type is notSend. - Reaching for it too early. A wrapper like
Mutex<*mut T>still fails, because*mut Tis notSendand theMutexinherits that. ButArc<Mutex<Box<T>>>often replaces a hand-written type entirely.
Exercise
A colleague writes struct Slot<T> { ptr: *const T } as a non-owning view into a buffer, then adds unsafe impl<T> Send for Slot<T> {} and unsafe impl<T> Sync for Slot<T> {}. Name the problem, and write the bounds you would use if Slot<T> behaves like &T.
Show answer
Neither impl has bounds on T, so a Slot<Cell<i32>> or Slot<Rc<i32>> could be shared or sent across threads and cause a data race. Because Slot<T> acts like &T, mirror the rules for &T: unsafe impl<T: Sync> Send for Slot<T> {} (sending &T requires T: Sync) and unsafe impl<T: Sync> Sync for Slot<T> {}. You must also be sure the buffer outlives every thread that holds a Slot.
Exercise
Why does Handle in this chapter implement Send but not Sync?
Show answer
Moving a Handle gives one thread exclusive access to its allocation, so no race can occur. But bump(&self) mutates through a raw pointer without synchronization. If Handle were Sync, two threads could call bump on a shared &Handle at the same time, which is a data race.