Sub topic 13
dyn Trait + Send + Sync
This chapter assumes you know Box<dyn Trait>, Arc, and thread::spawn. It also assumes you know what Send and Sync mean for ordinary types.
Why a trait object may not be Send
Send and Sync are auto traits. The compiler implements them for a type when all of its fields have them. A trait object hides the concrete type, so the compiler can't see the fields. It therefore assumes nothing. dyn Greeter is not Send and not Sync unless the type says so.
Adding auto traits to the type
You can add auto traits to a trait object type with +:
dyn Greeter + Sendmeans any value behind it can move to another thread.dyn Greeter + Syncmeans a shared reference to it can cross threads.dyn Greeter + Send + Syncmeans both.
This is the working example:
use std::sync::Arc;
use std::thread;
trait Greeter {
fn greet(&self) -> String;
}
struct English;
impl Greeter for English {
fn greet(&self) -> String {
String::from("hello")
}
}
fn main() {
let g: Arc<dyn Greeter + Send + Sync> = Arc::new(English);
let g2 = Arc::clone(&g);
let handle = thread::spawn(move || g2.greet());
println!("{} {}", handle.join().unwrap(), g.greet());
}It prints hello hello.
Arc<T> is Send only when T is both Send and Sync. That is why the Arc needs both bounds. A Box<dyn Trait + Send> is enough when you move ownership into one thread and never share it.
The check happens at coercion
The compiler checks the bounds where a concrete type becomes a trait object. If English held an Rc<String>, this line would not compile:
let g: Arc<dyn Greeter + Send + Sync> = Arc::new(English);The error appears on that line, not at the later thread::spawn. This helps you, because you find the problem where the type is erased.
Types are distinct, but some conversions work
dyn Greeter + Send and dyn Greeter are different types. You can drop a bound, but you can't add one:
| From | To | Allowed |
|---|---|---|
| `Box<dyn Greeter + Send>` | `Box<dyn Greeter>` | Yes |
| `Box<dyn Greeter>` | `Box<dyn Greeter + Send>` | No |
| `&(dyn Greeter + Sync)` | `&dyn Greeter` | Yes |
Only auto traits can follow the main trait this way. A type like dyn Greeter + Display is an error, because a trait object may have only one non-auto trait. Combine two traits through a supertrait or a new trait that requires both.
Bounds in the trait or in the type
You can put the requirement on the trait itself with a supertrait:
use std::thread;
trait Job: Send {
fn run(&self) -> u32;
}
struct Add(u32, u32);
impl Job for Add {
fn run(&self) -> u32 {
self.0 + self.1
}
}
fn main() {
let jobs: Vec<Box<dyn Job>> = vec![Box::new(Add(1, 2)), Box::new(Add(3, 4))];
let handle = thread::spawn(move || jobs.iter().map(|j| j.run()).sum::<u32>());
println!("{}", handle.join().unwrap());
}This prints 10. Every dyn Job is Send, so callers never write the bound. The cost is that every implementor must be Send, even in single-threaded programs. Putting + Send in the type keeps the trait general and makes each use site choose.
A type alias keeps long signatures readable:
type Handler = Box<dyn Fn(u32) -> u32 + Send + Sync + 'static>;Here 'static is the default for Box<dyn ...>. It is written out only to show where a lifetime bound goes.
Common errors
- Forgetting
+ Sendon a boxed closure passed to a thread or task spawner. - Writing
Arc<dyn Trait + Send>and then sharing it. You needSyncas well. - Expecting
Box<dyn Trait>to convert intoBox<dyn Trait + Send>. You must create it with the bound from the start.
Exercise
A function takes Arc<dyn Cache + Send> and clones the Arc into several spawned threads. The code does not compile. What is wrong and how do you fix it?
Show answer
An Arc<T> is Send only if T is both Send and Sync. The type has Send but not Sync, so the Arc can't cross threads. Change the type to Arc<dyn Cache + Send + Sync>, and make sure every concrete Cache implementation is Send + Sync.