A Rust metrics library wraps a C handle as `*mut c_void`; when is `unsafe impl Send` justified, and what would `unsafe impl Sync` add?
answer
- raw pointers block the auto impl
- what the C library documents
- transfer versus concurrent &self calls
- edition 2021 captures fields separately
basics
~20 sunsafe impl Send is justified when the C library allows a handle to be used and freed off its creating thread and the wrapper owns it exclusively; unsafe impl Sync also promises that concurrent &self calls are safe.
solid answer
~50 sA struct holding `*mut c_void` is neither `Send` nor `Sync`, because raw pointers opt out and auto traits follow fields; `thread::spawn` then fails with E0277 "`*mut c_void` cannot be sent between threads safely". `unsafe impl Send for MetricsHandle {}` promises that moving the wrapper to another thread, using it and dropping it there is sound. That holds when the C library has no thread affinity for handles (no thread-local state, no "free on the creating thread" rule) and the wrapper is the only owner of the pointer. `unsafe impl Sync` is a separate promise: several threads may call `&self` methods at the same moment, so the library must document concurrent calls on one handle as safe. If it does not, leave the type `!Sync` and let callers use `Mutex<MetricsHandle>`, which is `Sync` because the handle is `Send`. Without `unsafe`, rustc rejects the impl with E0200.
code
rust · 24 linesuse std::ffi::c_void;
use std::thread;
// Stands in for an opaque handle from a C library that documents its
// functions as callable from any thread, one caller at a time.
struct MetricsHandle {
raw: *mut c_void,
}
// SAFETY: the C library allows a handle to be used from any thread, and
// MetricsHandle owns its handle exclusively, so moving it is sound.
unsafe impl Send for MetricsHandle {}
impl MetricsHandle {
fn flush(&mut self) -> usize {
self.raw as usize // a real wrapper would call the C flush function here
}
}
fn main() {
let mut h = MetricsHandle { raw: std::ptr::null_mut() };
let t = thread::spawn(move || h.flush());
println!("flushed: {}", t.join().unwrap());
}go deeper
Recall that a struct holding a raw pointer is not Send or Sync, and that making it so needs an unsafe impl someone must justify.
Explain why raw pointers opt out, the E0200 error without unsafe, and how edition 2021 field capture can bypass the wrapper's impl.
Derive the Send and Sync decisions from the C library's threading contract, implement only what it supports, and point callers to Mutex when Sync is not justified.
Require a SAFETY comment citing the foreign library's threading guarantees on every unsafe impl Send or Sync, and review them like any other unsafe code.
## Why the wrapper is not Send to begin with A typical binding stores the C library's opaque handle in a raw pointer: ```rust struct MetricsHandle { raw: *mut c_void, } ``` `*const T` and `*mut T` carry negative impls of both `Send` and `Sync` in `core::marker`, and auto traits are computed from fields, so `MetricsHandle` is neither. The Nomicon is candid that this is partly a lint: a raw pointer can do nothing without `unsafe` anyway, but marking it thread-unsafe stops types that contain one from being declared thread-safe by accident, because their author may never have thought about threads. `std::ptr::NonNull` is no escape: it is also `!Send` and `!Sync`. Moving the wrapper into `thread::spawn` produces E0277, and the notes walk the chain: "`*mut c_void` cannot be sent between threads safely", "required because it appears within the type `MetricsHandle`", "required by a bound in `spawn`". ## What `unsafe impl Send` promises `Send` and `Sync` are `unsafe trait`s, so a manual impl must be written `unsafe impl`; leaving out `unsafe` fails with E0200 "the trait `Send` requires an `unsafe impl` declaration". The `unsafe` keyword marks a promise that the compiler cannot check. For `Send` the promise is: **a value of this type may be moved to another thread, used there and dropped there without undefined behaviour.** For a C handle, that comes down to facts about the library and about your wrapper: - **No thread affinity.** The library must allow a handle created on one thread to be used and freed on another. Libraries that keep per-thread state, or that require cleanup on the creating thread, fail this test. - **Exclusive ownership.** The wrapper must be the only holder of the pointer. If the library or another Rust value keeps an alias and touches it concurrently, moving the wrapper does not move all access. - **Drop does the right thing.** The wrapper's `Drop` impl calls the library's free function once, and that call is itself allowed on any thread. - **Generic bounds.** A generic wrapper such as `Handle<T>` writes `unsafe impl<T: Send> Send for Handle<T>`; omitting the bound would let a non-`Send` `T` ride along. Record the reasoning in a `// SAFETY:` comment above the impl, citing the C library's threading documentation. ## What `unsafe impl Sync` adds `Sync` promises something stronger and different: **several threads may hold `&MetricsHandle` and call its `&self` methods at the same time.** That is justified only if: 1. the C library documents that concurrent calls on *one* handle are safe (it locks internally, or the operations are atomic), and 2. every `&self` method in your wrapper only makes calls the library allows concurrently. Many C libraries document that a handle may be used from any thread, but not from two threads at once. That is a `Send`-but-not-`Sync` contract. Leave the type `!Sync` and let callers choose `Mutex<MetricsHandle>` or `Arc<Mutex<MetricsHandle>>`: `Mutex<T>` is `Sync` whenever `T: Send`, so the `Send` impl you justified is enough. | Library contract | `unsafe impl Send` | `unsafe impl Sync` | |---|---|---| | handle bound to its creating thread | no | no | | any thread, one caller at a time | yes | no — use `Mutex` | | any thread, concurrent calls safe | yes | yes | Proving that the impls are sound for a particular library, and auditing unsafe code around them, belongs to the lesson on sound safe abstractions. ## The edition 2021 capture trap Even with a correct `unsafe impl Send for MetricsHandle`, this fails: ```rust let t = thread::spawn(move || h.raw as usize); ``` Since the 2021 edition, closures capture **disjoint fields**: the closure captures only `h.raw`, a bare `*mut c_void`, not the whole `MetricsHandle`, so your impl never applies and rustc reports E0277 for `*mut c_void`. The edition guide describes exactly this case. Fixes: - call a method that takes the whole value (`move || h.flush()`), or - rebind inside the closure (`let h = h;`) so the struct is captured, or - keep the field private so callers can only reach it through methods. ## A checklist before writing the impl - Read the C library's threading section and quote it in the `SAFETY` comment. - Implement only the trait the documentation supports; `Send` without `Sync` is common and correct. - Keep the raw pointer private, so the promise covers every way the handle can be reached. - Test the cross-thread path, knowing a test that passes does not prove soundness.
- The C documentation says a handle must be destroyed on the thread that created it; can you still make the wrapper `Send`?Not as a plain owning wrapper, because a moved wrapper would run the free function on the wrong thread when dropped. Keep it `!Send`, or redesign: confine the handle to one dedicated thread and send it requests over a channel, so only that thread ever touches or frees the handle.
- Why does storing the pointer as `NonNull<c_void>` instead of `*mut c_void` not help?`NonNull<T>` is also `!Send` and `!Sync`; std documents that the data it points at may be aliased. It improves the type (non-null, covariant, enables niche optimisation) but leaves the thread-safety decision to an explicit `unsafe impl`, exactly as with a raw pointer.
- Add unsafe impl Send and Sync together; they mean the same thing.
- Raw pointers are not Send because dereferencing them is slow across threads.
- If a quick multithreaded test passes, the unsafe impl is sound.
- Switching the field to NonNull makes the wrapper Send.
- The unsafe keyword on the impl is optional for marker traits.