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 type's fields. It also assumes you can read an unsafe impl. Here you will make your own types refuse to cross threads, and learn when that is the right call.
Why a type would refuse threads
Most of the time the compiler gives you Send and Sync for free, and that is what you want. Some types need to stay on one thread even though their fields would normally allow a move:
- A handle to a C library that keeps state in thread-local storage, or that requires every call to come from the thread that created it.
- A guard that must be released on the thread that acquired it.
MutexGuardis the standard example, because some platform lock implementations require the unlocking thread to be the locking thread. - A token that stands for "this thread is inside some context", such as a GIL-style token or a GUI main-thread proof.
- A type whose internal bookkeeping uses non-atomic interior mutability, which you want to keep as an implementation detail.
In these cases Send or Sync would be a false promise. Because the traits are auto traits, the compiler grants them unless a field says no. Opting out therefore means making a field say no.
Two ways to opt out
There are two mechanisms.
- Negative impls:
impl !Send for MyType {}. This is the direct way, but it needs the unstablenegative_implsfeature and a nightly compiler. The standard library uses it internally. Stable code cannot write it. - A marker field: add a zero-sized field whose type is not
Sendor notSync. Auto-trait derivation is structural, so one such field removes the trait from the whole struct. This works on stable Rust, and it is what you should use.
The usual marker field is PhantomData<T>. PhantomData<T> is zero-sized, and it is Send exactly when T is Send, and Sync exactly when T is Sync. You get the thread-safety effect of holding a T without storing one.
| You want the type to be | Marker field | Why it works |
|---|---|---|
| Neither `Send` nor `Sync` | `PhantomData<*const ()>` | Raw pointers are neither |
| `Send` but not `Sync` | `PhantomData<Cell<()>>` | `Cell<()>` is `Send`, not `Sync` |
| `Sync` but not `Send` | `PhantomData<MutexGuard<'static, ()>>` | `MutexGuard<'_, ()>` is `Sync`, not `Send` |
| Always both, whatever `T` is | `PhantomData<fn() -> T>` | Function pointers are `Send + Sync` |
The last row is the reverse case. PhantomData<T> for a generic T makes your type inherit T's restrictions. If you only want a type tag, PhantomData<fn() -> T> avoids that.
A worked example
This program defines three types with different restrictions. It also defines a type that is Send + Sync for comparison. It checks the results with the same bound-asserting functions you saw earlier in the tutorial.
use std::cell::Cell;
use std::marker::PhantomData;
use std::sync::MutexGuard;
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
/// Must stay on the thread that created it.
struct ThreadBound {
id: u32,
_not_send_or_sync: PhantomData<*const ()>,
}
/// May move between threads, but must not be shared by reference.
struct MovableOnly {
id: u32,
_not_sync: PhantomData<Cell<()>>,
}
/// May be shared by reference, but must not be moved to another thread.
struct SharedOnly {
id: u32,
_not_send: PhantomData<MutexGuard<'static, ()>>,
}
/// Ordinary type, both traits derived automatically.
struct Plain {
id: u32,
}
impl ThreadBound {
fn new(id: u32) -> Self {
ThreadBound { id, _not_send_or_sync: PhantomData }
}
}
fn main() {
assert_send::<Plain>();
assert_sync::<Plain>();
assert_send::<MovableOnly>();
assert_sync::<SharedOnly>();
// Each of these lines would fail to compile if uncommented:
// assert_send::<ThreadBound>();
// assert_sync::<ThreadBound>();
// assert_sync::<MovableOnly>();
// assert_send::<SharedOnly>();
let t = ThreadBound::new(7);
println!("{}", t.id);
let _ = (MovableOnly { id: 1, _not_sync: PhantomData }.id,
SharedOnly { id: 2, _not_send: PhantomData }.id,
Plain { id: 3 }.id);
}ThreadBound works on its own thread, where it can be created, read and dropped. If you try to hand it to thread::spawn, the compiler reports that *const () cannot be sent between threads safely. The error names the marker field, which makes the cause easy to find.
Edge cases and gotchas
A marker must be a field, not a bound
Auto traits look at fields. A where clause or a trait bound does not remove Send from a type. If you write struct Foo<T: Send>, that only restricts which T you may use. It does not stop Foo<T> from being Send when the fields allow it.
An `unsafe impl` overrides your marker
Suppose your type has a raw pointer for real reasons and you also write unsafe impl Send for MyType {}. Then you have opted in, and the marker is irrelevant. The reverse also holds. If you want a type to be !Send, do not write unsafe impl Send for it.
Marker fields affect more than thread safety
PhantomData<T> also affects variance and drop checking.
PhantomData<*const T>is covariant inT.PhantomData<*mut T>is invariant. Picking the wrong one can change whether your lifetimes compose.PhantomData<T>tells the drop checker that your type may own aT.
If your type already uses T in a real field, these effects are already settled. If it does not, check the marker you choose with PhantomData<*const ()>, which has no generic parameter and so no variance effect.
Opting out is part of your public API
Whether a type is Send or Sync is visible to users, and it is covered by semver:
- Adding a non-
Sendfield to a public type that wasSendis a breaking change. Downstream code that spawned threads with it stops compiling. - Removing an opt-out is not breaking.
- The restriction also leaks through
impl Traitreturn types and through generic wrappers. If a public function returnsimpl Iterator, the hidden type'sSendstatus is visible to callers.
Decide on the thread-safety story of a public type early, and write it in the documentation.
Opting out does not prevent unsound code on its own
!Send only stops safe code from moving a value to another thread. It does not stop a 'static global or a pointer you leak through FFI. If thread affinity is a real safety invariant, such as a C library that crashes on cross-thread use, also design the API so the invariant is hard to break. Expose only methods that go through the owning handle, and keep raw pointers private.
Testing that an opt-out holds
An opt-out is easy to lose by accident. A refactor can replace the marker field, or someone can add an unsafe impl. A compile-fail doctest guards against this:
/// ```compile_fail
/// use my_crate::ThreadBound;
/// fn needs_send<T: Send>(_: T) {}
/// needs_send(ThreadBound::new(1));
/// ```
pub struct ThreadBound { /* ... */ }The doctest passes only while the code fails to compile. It stops passing when someone makes the type Send again, which tells you the guarantee was lost. Keep one such test per opt-out, and add a positive assert_send test for every type you intend to be Send.
Exercise
You are writing struct Session that wraps a non-atomic counter in a Cell<u32> and also holds a PhantomData<MutexGuard<'static, ()>> field. Is Session Send? Is it Sync? Which single field would you change to make it Send but still not Sync?
Show answer
Session is not Send, because MutexGuard is not Send and auto traits apply to every field. It is also not Sync, because Cell<u32> is not Sync. To make it Send but not Sync, remove the MutexGuard marker (or replace it with PhantomData<Cell<()>>). The Cell<u32> field already removes Sync, and Cell<u32> is Send, so no other change is needed.
Exercise
A library author adds PhantomData<Rc<()>> to a public struct that previously had only u64 and String fields, as a way to document that the type should stay on one thread. Name two consequences for users of the library.
Show answer
First, the struct is no longer Send or Sync, so any user code that moved it into thread::spawn, shared it through Arc, or returned it from an async function that requires Send stops compiling. This makes the change a semver-breaking one. Second, any generic wrapper or impl Trait return type that contains the struct loses Send and Sync too, so the restriction spreads to types the author did not touch.