Sub topic 13
dyn Trait + Send + Sync
This chapter assumes you know how Box<dyn Trait> and &dyn Trait work. It also assumes you have used thread::spawn and Arc at a basic level. The question here is why a trait object is often not thread-safe by default, and how to say that it is.
Auto traits are not part of dyn Trait
Send and Sync are auto traits. The compiler implements them for a struct when all its fields implement them. A trait object has no fields the compiler can inspect. Behind dyn Trait there could be any type that implements Trait, including one that holds an Rc.
So the compiler assumes nothing. dyn Trait is neither Send nor Sync unless the type says so.
Sendmeans a value can be moved to another thread.Syncmeans a shared reference&Tcan be used from several threads at once. A typeTisSyncexactly when&TisSend.
Suppose a program does this:
let tasks: Vec<Box<dyn Task>> = vec![Box::new(Double(2))];
thread::spawn(move || tasks.iter().map(|t| t.run()).sum::<u32>());The compiler rejects it:
error[E0277]: `dyn Task` cannot be sent between threads safelyThe rejection is correct. Another implementor of Task could hold an Rc, and moving that to another thread would be a data race.
Adding Send at the use site
You can add one or more auto traits to a trait object type with +. Here the vector holds Box<dyn Task + Send>:
use std::thread;
trait Task {
fn run(&self) -> u32;
}
struct Double(u32);
impl Task for Double {
fn run(&self) -> u32 {
self.0 * 2
}
}
fn main() {
let tasks: Vec<Box<dyn Task + Send>> = vec![Box::new(Double(2)), Box::new(Double(5))];
let handle = thread::spawn(move || tasks.iter().map(|t| t.run()).sum::<u32>());
println!("{}", handle.join().unwrap());
}This prints 14. The bound is checked where the box is created. Box::new(Double(2)) coerces to Box<dyn Task + Send> only if Double is Send. If you tried this with a type that contains an Rc, the error would appear at the coercion, not at thread::spawn.
Here is the rule for +. A trait object type may name exactly one non-auto trait. It may add any number of auto traits and one lifetime. dyn Task + Send + Sync + 'static is valid. dyn Task + Debug is not. For two non-auto traits, define a new trait that has both as supertraits and implement it for everything that has both:
use std::fmt::Debug;
trait Task {
fn run(&self) -> u32;
}
trait DebugTask: Task + Debug {}
impl<T: Task + Debug> DebugTask for T {}
#[derive(Debug)]
struct Double(u32);
impl Task for Double {
fn run(&self) -> u32 {
self.0 * 2
}
}
fn main() {
let t: Box<dyn DebugTask + Send> = Box::new(Double(4));
println!("{:?} -> {}", t, t.run());
}This prints Double(4) -> 8.
Supertrait or use-site bound?
You can also require Send in the trait itself:
trait Job: Send {
fn run(&self) -> u32;
}Then every dyn Job is Send, and no implementor can contain a non-Send field. The two approaches differ as follows.
| Approach | Effect | Trade-off |
|---|---|---|
| `trait Job: Send` | Every implementor and every `dyn Job` is `Send`. | Single-threaded users cannot implement `Job` with `Rc` fields. |
| `dyn Job + Send` | Only the places that need `Send` ask for it. | Signatures get longer, and callers must write the bound everywhere. |
Library traits meant for general use usually leave the bound at the use site. A trait inside an application that always runs on a thread pool is simpler with the supertrait.
A type alias removes the repetition:
trait Task {
fn run(&self) -> u32;
}
type BoxedTask = Box<dyn Task + Send + 'static>;
struct Double(u32);
impl Task for Double {
fn run(&self) -> u32 {
self.0 * 2
}
}
fn plain(t: Box<dyn Task>) -> u32 {
t.run()
}
fn main() {
let t: BoxedTask = Box::new(Double(21));
// Dropping auto traits is allowed: dyn Task + Send coerces to dyn Task.
println!("{}", plain(t));
}This prints 42. dyn Task + Send and dyn Task are different types, but the compiler converts from the stronger one to the weaker one. The reverse direction does not compile, because it would add a guarantee that nothing checked.
How Send and Sync flow through pointers
A pointer to a trait object is Send or Sync depending on the pointer type and on what the trait object promises. This table lists the rules for the standard pointer types, where dyn T stands for the whole trait object type including its auto traits:
| Type | Is Send when | Is Sync when |
|---|---|---|
| `Box<dyn T>` | `dyn T` is `Send` | `dyn T` is `Sync` |
| `&dyn T` | `dyn T` is `Sync` | `dyn T` is `Sync` |
| `&mut dyn T` | `dyn T` is `Send` | `dyn T` is `Sync` |
| `Arc<dyn T>` | `dyn T` is `Send` and `Sync` | `dyn T` is `Send` and `Sync` |
| `Rc<dyn T>` | never | never |
Two rows matter most in practice.
&dyn TneedsSync, notSend. Sending a shared reference to another thread lets both threads read the value at once. That is only safe if the type isSync. Scoped threads show this: borrowing&(dyn Task + Sync)into a scope works, and borrowing&dyn Taskdoes not.Arc<dyn T>needs both.Arccan be cloned to other threads and dropped on any of them. Dropping on another thread needsSend, and shared access needsSync. SoArc<dyn T>is thread-safe only if you writeArc<dyn T + Send + Sync>.
use std::sync::Arc;
use std::thread;
trait Greeter {
fn greet(&self) -> String;
}
struct English;
struct French;
impl Greeter for English {
fn greet(&self) -> String {
String::from("hello")
}
}
impl Greeter for French {
fn greet(&self) -> String {
String::from("bonjour")
}
}
fn main() {
let greeters: Vec<Arc<dyn Greeter + Send + Sync>> = vec![Arc::new(English), Arc::new(French)];
let mut handles = Vec::new();
for g in &greeters {
let g = Arc::clone(g);
handles.push(thread::spawn(move || g.greet()));
}
for h in handles {
println!("{}", h.join().unwrap());
}
}This prints hello and then bonjour. Handles are joined in spawn order, so the output order is stable.
Mutation across threads
A trait with &mut self methods cannot be shared as plain Arc<dyn Trait>. Put a Mutex around the trait object. Mutex<T> is Sync when T: Send, so the contents need Send but not Sync:
use std::sync::{Arc, Mutex};
use std::thread;
trait Counter {
fn bump(&mut self) -> u32;
}
struct Simple(u32);
impl Counter for Simple {
fn bump(&mut self) -> u32 {
self.0 += 1;
self.0
}
}
fn main() {
let shared: Arc<Mutex<dyn Counter + Send>> = Arc::new(Mutex::new(Simple(0)));
let handles: Vec<_> = (0..4)
.map(|_| {
let c = Arc::clone(&shared);
thread::spawn(move || {
c.lock().unwrap().bump();
})
})
.collect();
for h in handles {
h.join().unwrap();
}
println!("{}", shared.lock().unwrap().bump());
}This prints 5: four increments from the threads and one from the main thread. The Arc<Mutex<Simple>> coerces to Arc<Mutex<dyn Counter + Send>> because Mutex<T> allows an unsized T.
Common errors
- Missing
'staticwiththread::spawn.Box<dyn Task + Send>in a field defaults todyn Task + Send + 'static. A&dyn Task + Sendborrowed from the stack has a shorter lifetime, andspawnrejects it. Usethread::scopeor an ownedBoxorArc. - Adding
Sendto the wrong place.Box<dyn Task> + Sendis a syntax error. The bound goes inside:Box<dyn Task + Send>. - Requiring
SyncforMutexcontents.Arc<Mutex<dyn Counter + Send>>is enough. RequiringSyncas well would reject types likeCellfields that are safely usable behind a lock. - Implementor not
Send. The error names the concrete type at the coercion site, such asRc<i32>cannot be sent between threads safely. ReplaceRcwithArc, or drop theSendrequirement if the code is single-threaded.
Exercise
You have trait Plugin { fn name(&self) -> String; } and a Vec<Arc<dyn Plugin>>. Passing a clone of one element into thread::spawn fails to compile. What type change fixes it, and why is Send alone not enough?
Show answer
Change the element type to Arc<dyn Plugin + Send + Sync>. Cloned Arcs are held by several threads at once, so the value behind them must be Sync (shared access is safe). Each Arc can also be dropped on any thread, so the value must be Send. Arc<T> is Send only when T is both Send and Sync. Every concrete plugin placed in the vector must then also be Send + Sync.
Exercise
Given fn show(t: Box<dyn Task>) and a value b: Box<dyn Task + Send>, does show(b) compile? Does passing a Box<dyn Task> to a function that takes Box<dyn Task + Send> compile?
Show answer
show(b) compiles, because the compiler can coerce dyn Task + Send to dyn Task by dropping an auto trait. The reverse does not compile. A Box<dyn Task> has lost the information about its concrete type, so the compiler cannot prove it is Send.