Sub topic 15
Opting out of Send and Sync in your own types
This chapter assumes you know how auto traits derive Send and Sync from a struct's fields. It also assumes you know what PhantomData is and how unsafe impl works. Here you will learn how to make your own type refuse to cross threads, even when all its fields would allow it.
Why opt out on purpose
The compiler gives a struct Send and Sync when every field has them. That is sometimes wrong for your design. A few examples:
- A handle that wraps thread-local state, such as a per-thread cache index.
- A guard that must be dropped on the thread that created it, like
MutexGuard. - A wrapper around an OS or FFI resource that must be used from one thread, such as a GUI toolkit object.
None of these contain a field that is unsafe to move. The rule lives in your API, so you have to encode it in the type.
Stable opt-out with PhantomData
PhantomData<T> takes up no space, but it counts as a field of type T when the compiler derives auto traits. Put a field in it that lacks the trait you want to remove.
| Marker field | Send | Sync | Result for your type |
|---|---|---|---|
| `PhantomData<*const ()>` | no | no | Neither trait |
| `PhantomData<Cell<()>>` | yes | no | Send only |
| `PhantomData<std::sync::MutexGuard<'static, ()>>` | no | yes | Sync only |
use std::cell::Cell;
use std::marker::PhantomData;
struct ThreadBound {
id: u32,
_not_send_or_sync: PhantomData<*const ()>,
}
struct SendOnly {
id: u32,
_not_sync: PhantomData<Cell<()>>,
}
impl ThreadBound {
fn new(id: u32) -> Self {
ThreadBound { id, _not_send_or_sync: PhantomData }
}
}
impl SendOnly {
fn new(id: u32) -> Self {
SendOnly { id, _not_sync: PhantomData }
}
}
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
fn main() {
let a = ThreadBound::new(1);
let b = SendOnly::new(2);
println!("{} {}", a.id, b.id);
assert_send::<SendOnly>();
// Each of these lines fails to compile if uncommented:
// assert_send::<ThreadBound>();
// assert_sync::<ThreadBound>();
// assert_sync::<SendOnly>();
}The program prints 1 2. The three commented lines show the opt-out working, because the compiler reports that the trait bound is not satisfied.
Negative impls are nightly only
The direct way to write this is impl !Send for ThreadBound {}. That syntax needs the unstable negative_impls feature, so it only works on nightly. Standard library types such as Rc use it internally. In stable code, use the PhantomData marker.
Opting back in
An opt-out is not permanent. If a type holds a raw pointer, you can add unsafe impl Send later, as in the OwnedPtr example from the previous chapter. You cannot undo a PhantomData marker by adding an unsafe impl for a type that is not meant to move. Decide first whether the restriction is a real invariant or only a side effect of a field.
Common mistakes
- Using
PhantomData<Rc<()>>instead of*const (). It works, but it hints at reference counting that is not there. - Forgetting the marker when the type holds only plain integers. Nothing else will stop it from crossing threads.
- Adding
unsafe impl Sendto silence an error on a type that has a thread-affinity rule.
Exercise
You are writing GlContext, which stores a u64 handle and must stay on the thread that created it. It can be moved but not shared by reference between threads... or can it? Which marker would you choose to make it neither Send nor Sync, and why is a plain u64 field not enough?
Show answer
Add a field of type PhantomData<*const ()>. A u64 is both Send and Sync, so the compiler would derive both traits for GlContext automatically. The raw pointer inside PhantomData is neither, so the derived result is neither Send nor Sync.