Sub topic 2
Send and Sync Are Marker Traits
This chapter assumes you know how traits, trait bounds and generics work, how move closures capture values, and how to start a thread with std::thread::spawn and wait for it with JoinHandle::join. It explains what kind of trait Send and Sync are, where they live, and how they show up in code you write. Later chapters cover what each one promises and how the compiler decides which types have them.
What a marker trait is
A marker trait is a trait with no methods, no associated types and no associated constants. Implementing it adds nothing you can call. It records a fact about a type, and other code can require that fact through a trait bound.
Here is a marker trait you can define yourself:
trait Billable {}
struct Invoice;
struct Receipt;
impl Billable for Invoice {}
fn charge<T: Billable>(_item: &T) {
println!("charged");
}
fn main() {
charge(&Invoice);
// charge(&Receipt); // error: the trait bound `Receipt: Billable` is not satisfied
let _ = Receipt;
}charge accepts only types that opted in. The compiler checks this when it compiles the program. The check generates no machine code and has no cost at run time. The trait exists so the compiler can accept or reject programs.
Send and Sync use the same mechanism. The fact they record is whether a type is safe to use across threads.
Where Send and Sync are defined
Both traits are defined in std::marker. Their declarations in the standard library look like this:
pub unsafe auto trait Send { }
pub unsafe auto trait Sync { }The auto trait syntax is unstable, so you cannot write these lines in your own crate on stable Rust. You do not need to. You only use the two traits, as bounds and occasionally with unsafe impl.
The two keywords in those declarations make Send and Sync different from Billable:
unsafemeans that implementing the trait is a promise the compiler cannot check. If your promise is false, safe code can cause a data race, so you must writeunsafe impl.automeans the compiler implements the trait for you. A type getsSendwhen all of its fields areSend, and likewise forSync. You normally never writeimpl Send for MyType.
The chapter on auto traits covers the derivation rules. For now, remember that the default is automatic, and writing it by hand is the rare case.
What each trait says
The details come in the next two chapters. A short version helps you read bounds now:
T: Sendmeans a value of typeTcan be moved to another thread, so the other thread takes over ownership.T: Syncmeans a shared reference&Tcan be used from several threads at once.
Both are properties of a type. A type can have one, both or neither. The standard library lists several marker traits, and the table puts these two beside the others.
| Trait | Fact it records | Automatic? | Unsafe to implement? |
|---|---|---|---|
| `Send` | Ownership can move to another thread | Yes | Yes |
| `Sync` | `&T` can be shared across threads | Yes | Yes |
| `Copy` | Duplicating the bits is a valid copy | No, you derive or implement it | No |
| `Sized` | The size is known at compile time | Yes, the compiler decides | Not implementable by hand |
| `Unpin` | The value may be moved after being pinned | Yes | No |
Copy is a marker too, but you opt in with #[derive(Copy, Clone)]. Send and Sync are different because you opt out. A type that holds a raw pointer, for example, is not Send until its author says it is.
The diagram below shows how the markers group by who decides.
Where the bounds appear
Most of the time you meet Send and Sync in the signatures of library functions. thread::spawn requires its closure to be Send. You can write the same bound on your own functions:
use std::thread::{self, JoinHandle};
fn run_elsewhere<F>(job: F) -> JoinHandle<()>
where
F: FnOnce() + Send + 'static,
{
thread::spawn(job)
}
fn main() {
let name = String::from("worker");
let handle = run_elsewhere(move || println!("hello from {name}"));
handle.join().unwrap();
}Here F: Send is satisfied because the closure captures only a String, and String is Send. Because Send is automatic, a closure is Send exactly when everything it captures is Send. You never declare it.
A bound on your own function matters because it moves the error. Without Send on run_elsewhere, the failure would appear inside thread::spawn. With the bound, the error points at the call site where the caller passed a bad closure.
Asking the compiler about a type
You can test a type with two empty generic functions. This is the quickest way to learn whether a type is Send or Sync:
use std::cell::Cell;
use std::sync::Mutex;
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
fn main() {
assert_send::<String>();
assert_sync::<Vec<i32>>();
assert_send::<Cell<i32>>();
assert_sync::<Mutex<i32>>();
println!("all checks passed");
}The functions do nothing at run time. The call is the test. If a bound is not met, the program does not compile. The same helpers also work as compile-time tests for your own types, so a later refactor that adds an Rc field breaks the build instead of surprising a caller.
Trait objects need the marker spelled out
A trait object type such as Box<dyn FnOnce()> hides the concrete type behind it, so the compiler cannot know whether that type is Send. Auto traits are therefore not assumed for dyn Trait. You add them to the type:
use std::thread;
fn make_job() -> Box<dyn FnOnce() + Send + 'static> {
let msg = String::from("job ran");
Box::new(move || println!("{msg}"))
}
fn main() {
let job = make_job();
thread::spawn(job).join().unwrap();
}If you drop + Send from the return type, thread::spawn(job) stops compiling, even though the closure inside is Send. The return type is all the caller sees, and it no longer promises thread safety.
Common mistakes
- Treating the traits as a run-time check. Nothing is tested when the program runs. The compiler decides during compilation, and a type that is not
Sendsimply cannot be passed to a function that requiresSend. - Writing
impl Send for T {}withoutunsafe. The compiler rejects this becauseSendis an unsafe trait. Addingunsafemakes it compile, but it also makes you responsible for the promise. Do that only for the reasons given in the chapter on manual implementations. - Expecting a marker to add behavior. There are no methods to call. If you want to know whether a type is
Send, you can only ask through a bound, as inassert_send. - Forgetting that
SendandSyncare separate.Cell<i32>isSendbut notSync, as the check above shows. A type being usable in one way says nothing about the other.
Exercise
The Billable trait has no methods. Name two things it still does for your program, and say what it costs at run time.
Show answer
It restricts which types a generic function such as charge accepts, and it makes the compiler reject calls with types that did not opt in. It also documents a fact about the type in code. It costs nothing at run time, because the check happens during compilation and no code is generated for the trait itself.
Exercise
A function returns Box<dyn FnOnce() + 'static> and the caller passes the result to thread::spawn. The closure inside captures only a String. Why does the program fail to compile, and what is the fix?
Show answer
The return type does not say the trait object is Send, and auto traits are not assumed for dyn Trait. thread::spawn requires Send, so the check fails even though the real closure is Send. Change the return type to Box<dyn FnOnce() + Send + 'static>.
Exercise
Why does impl Send for MyType {} fail to compile, and what does adding unsafe change?
Show answer
Send is an unsafe trait, so every implementation must be written unsafe impl. The compiler cannot verify that moving MyType to another thread is safe. Writing unsafe impl Send for MyType {} compiles, but it states that you have checked the type, and a wrong claim can allow data races.