skip to content

In Rust, a type owning a heap value through `NonNull<T>` needs `unsafe impl Send` — which bounds on `T` make that impl sound, and why?

level: seniorimportance: should knowfreq 38%

answer

  1. NonNull opts out of auto traits
  2. the impl is your promise
  3. what crosses the thread with it
  4. Box, Arc and Mutex differ

basics

~20 s

NonNull<T> makes the type neither Send nor Sync. For a uniquely owning type, write unsafe impl<T: Send> Send and unsafe impl<T: Sync> Sync; leaving out T: Send lets an Rc cross threads, and that is unsound.

solid answer

~40 s

`Send` and `Sync` are auto traits, and std writes `impl !Send for NonNull<T>` and `impl !Sync for NonNull<T>`, so any struct holding one loses both. Restoring them takes `unsafe impl`, which rustc does not check: it is a promise that the type's invariant makes cross-thread use safe. The bounds have to match what another thread can then do with `T`. A unique owner like `Box` moves the `T` with it, so `Send` needs `T: Send`; a shared `&MyBox<T>` only gives out `&T`, so `Sync` needs `T: Sync`. With a bare `unsafe impl<T> Send`, `MyBox<Rc<i32>>` moves into `thread::spawn` and two threads update one non-atomic count, which Miri reports as a data race. Shared owners need more: `Arc<T>` requires `T: Send + Sync`.

code

rust · 30 lines
rust
use std::ptr::NonNull;
use std::rc::Rc;
use std::thread;

pub struct MyBox<T> {
    ptr: NonNull<T>, // owns one heap T; NonNull makes MyBox !Send and !Sync
}

impl<T> MyBox<T> {
    pub fn new(value: T) -> Self {
        MyBox { ptr: NonNull::from(Box::leak(Box::new(value))) }
    }
    pub fn get(&self) -> &T {
        // SAFETY: ptr came from Box::leak and stays valid while self lives.
        unsafe { self.ptr.as_ref() }
    }
}

// SAFETY: wrong - nothing stops T from being a thread-bound type like Rc.
unsafe impl<T> Send for MyBox<T> {} // sound version: impl<T: Send>

fn main() {
    let shared = Rc::new(1);
    let b = MyBox::new(Rc::clone(&shared));
    let h = thread::spawn(move || {
        for _ in 0..100 { drop(Rc::clone(b.get())); }
    });
    for _ in 0..100 { drop(Rc::clone(&shared)); } // same non-atomic count
    h.join().unwrap();
}

go deeper

for a junior

Recall that raw pointers and NonNull are neither Send nor Sync, so a struct holding one loses both traits, and restoring them needs unsafe impl.

for a middle

Explain why the impl is a promise rustc trusts and cannot check, and give the unique-owner bounds: Send needs T: Send, Sync needs T: Sync.

for a senior

Derive bounds from what another thread can do with T, contrast Box, Arc and Mutex from the std source, and show the Rc data race an unbounded impl allows.

for a principal

Treat every unsafe Send or Sync impl as a review hotspot with its own SAFETY comment and invariant, because one wrong bound turns safe code elsewhere into a data race.

## Why the auto traits switch off `Send` (safe to move to another thread) and `Sync` (safe to share by `&` between threads) are **auto traits**: a struct gets them when all of its fields have them. The basics belong to the material on threads; what matters here is that std deliberately opts raw pointers out. `core::marker` has `impl !Send for *const T` and `*mut T`, and `core::ptr` has `impl !Send for NonNull<T>` and `impl !Sync for NonNull<T>`. So a type such as ```rust pub struct MyBox<T> { ptr: NonNull<T> } ``` is neither `Send` nor `Sync`, even when `T` is a plain `String`. `thread::spawn(move || ...)` with one inside fails with "error[E0277]: `NonNull<String>` cannot be sent between threads safely". The compiler cannot know what the pointer means: an owned allocation, a borrow, a pointer into thread-local data or into a C library's object. ## The impl is a promise about your invariant Restoring the trait needs `unsafe impl`. A plain `impl<T: Send> Send for MyBox<T> {}` is rejected with "error[E0200]: the trait `Send` requires an `unsafe impl` declaration". The `unsafe` marks a claim rustc does not verify, and once you write it, `thread::spawn` and every other `Send`-bounded API trust it. If the claim is wrong, safe code elsewhere gets undefined behaviour and the bug is yours. The right question is: **when a value of my type crosses to another thread, what can that thread do with `T`?** 1. If it gains **ownership** of the `T`, so it can mutate it or drop it, it needs `T: Send`. 2. If it gains **shared access**, meaning `&T` while another thread may hold `&T` too, it needs `T: Sync`. 3. If two threads can end up **both owning and sharing**, as with reference counting, it needs both. For `MyBox`, `Sync` turns on what `&MyBox<T>` exposes. Today that is only `get(&self) -> &T`, so `T: Sync` is enough; adding a method that mutates the `T` through `&self` would change the answer, and the impl would need revisiting in the same change. ## Choosing the bounds | Type shape | `Send` impl needs | `Sync` impl needs | std example | |---|---|---|---| | Unique owner | `T: Send` | `T: Sync` | std's internal `Unique<T>` behind `Box` and `Vec` | | Shared, reference-counted owner | `T: Send + Sync` | `T: Send + Sync` | `Arc<T>` | | Lock giving one thread `&mut T` at a time | `T: Send` | `T: Send` | `std::sync::Mutex<T>` | All three rows are read from the 1.99.1 library source. `Mutex<T>` is the instructive one: it is `Sync` with only `T: Send`, because the lock hands each thread exclusive access in turn, which is effectively a move. `Arc<T>` needs both bounds even for `Send`, because a clone sent away shares the `T`, and whichever thread drops the last clone drops the `T`. ## What an unbounded impl lets safe code do With `unsafe impl<T> Send for MyBox<T> {}`, `MyBox<Rc<i32>>` is `Send`. A program can keep one `Rc` on the main thread, move a `MyBox` holding a clone into `thread::spawn`, and have both threads clone and drop the `Rc`. Both touch the same non-atomic reference count. The program compiles and even runs; Miri reports "Undefined Behavior: Data race detected between (1) non-atomic write on thread `main` and (2) non-atomic read on thread `unnamed-1`". With `T: Send` on the impl, rustc rejects the spawn with "error[E0277]: `Rc<i32>` cannot be sent between threads safely". ## Review checklist for an unsafe Send or Sync impl - Does every field other than the raw pointer already have the trait? If so, the bounds usually mirror the owning or sharing shape above. - Does the type contain **interior mutability** reachable through `&self`, such as a cached value or a counter? Then `Sync` needs synchronisation, not just a bound. - Is any resource **tied to its creating thread**, like a handle that a C library allows only on one thread? Then no bound on `T` makes `Send` sound. - Do clones **share state**, as `Rc` clones share a count? Then `Send` alone can be wrong even with `T: Send`. - Write a `// SAFETY:` comment on the impl stating the invariant it relies on. A fixed-capacity stack vector built on `[MaybeUninit<T>; N]` needs none of this: it holds no raw pointer, so it is `Send` and `Sync` exactly when `T` is, automatically.

  • Why does `Arc<T>` require `T: Send + Sync` even for `Arc<T>: Send`?
    Sending an `Arc` clone to another thread means two threads can hold `&T` at once, which needs `T: Sync`, and whichever thread drops the last clone drops the `T`, which needs `T: Send`. The 1.99.1 source states it directly: `unsafe impl<T: ?Sized + Sync + Send, A: Allocator + Send> Send for Arc<T, A>`.
  • Why is `std::sync::Mutex<T>` `Sync` when `T` is only `Send`?
    Sharing `&Mutex<T>` lets each thread lock it and get exclusive `&mut T` access, one thread at a time. No two threads see `&T` concurrently, so `T` never needs to be `Sync`; access passes between threads the way a moved value would, which is what `Send` covers. std writes `unsafe impl<T: ?Sized + Send> Sync for Mutex<T>`.
  • Can `unsafe impl<T: Send> Send` still be unsound?
    Yes. The bound only covers `T`. If the type also holds something bound to its creating thread, such as a pointer into thread-local storage or a handle a C library allows on one thread only, or if clones share non-atomic state, moving it is unsafe whatever `T` is. The impl must reflect the whole type's invariant.

  • unsafe impl<T> Send with no bound is fine because MyBox owns its T.
  • Adding PhantomData<T> beside NonNull<T> makes the type Send automatically.
  • If thread::spawn accepts the type, rustc has proved it safe to send.
  • A Sync impl always needs the same bound on T as the Send impl.
  • A plain impl Send for MyBox<T> works; unsafe is only a convention there.