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 how to use raw pointers in basic unsafe Rust.
Why you need an unsafe impl
A raw pointer such as *mut T is neither Send nor Sync. Any struct that contains one loses both traits. The compiler cannot tell whether the pointer is uniquely owned, shared, or dangling, so it plays safe.
If you know the pointer is uniquely owned, you can say so with unsafe impl. The keyword unsafe marks a promise the compiler cannot check. If the promise is false, safe code elsewhere can cause a data race.
A worked example
OwnedPtr<T> owns a heap allocation through a raw pointer. It behaves like Box<T>, so it gets the same rules as Box<T>.
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 assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
fn main() {
assert_send::<OwnedPtr<String>>();
assert_sync::<OwnedPtr<String>>();
// assert_send::<OwnedPtr<std::rc::Rc<i32>>>(); // fails to compile
let p = OwnedPtr::new(String::from("hello"));
let handle = thread::spawn(move || println!("{}", p.get()));
handle.join().unwrap();
}The program moves p into another thread and prints hello. The commented-out line shows that the bounds work. Rc<i32> is not Send, so OwnedPtr<Rc<i32>> is not Send either.
Choosing the bounds
The bounds on T are the part most often gotten wrong. Ask what your type lets a thread do with the T inside it.
| Your type behaves like | Send requires | Sync requires |
|---|---|---|
| `Box<T>`, `Vec<T>` (unique ownership) | `T: Send` | `T: Sync` |
| `Mutex<T>` (access through a lock) | `T: Send` | `T: Send` |
| `Arc<T>` (shared ownership) | `T: Send + Sync` | `T: Send + Sync` |
Mutex<T> needs only T: Send for Sync. The lock allows one thread at a time, so the value is never used from two threads at once. It may still be used from a different thread than the one that created it.
What you must guarantee
Before writing the impl, check each of these:
- Unique ownership or synchronized access. No two threads can mutate the same data without a lock or atomic.
- No thread-tied state. The type must not depend on thread-local data or on being dropped on the thread that created it. A
MutexGuardis not Send for this reason. - Sync means safe through
&self. Every method that takes&selfmust be safe to call from several threads at once.
Common errors
- Missing bounds. The impl is accepted but unsound, as in the warning above.
- Impl for convenience. Adding
unsafe impl Sendjust to silence a compiler error hides the real problem. Fix the type instead. - Aliased pointers. If you copy the raw pointer into two owners, both may free or mutate it. The unique-ownership argument no longer holds.
Exercise
You write a struct Shared<T> { ptr: *const T } that hands out &T to any thread but never mutates the value. What bounds do you put on unsafe impl Sync for Shared<T>, and why?
Show answer
Use unsafe impl<T: Sync> Sync for Shared<T> {}. Several threads can hold &Shared<T> at once, so each can read the &T inside, which is exactly what T: Sync allows. A bound of T: Send alone would be wrong, because T could be a type like Cell<i32> that is unsafe to read from two threads.