Send and Sync
In the previous lesson threads shared a counter through Arc. You already know a similar type for one thread — Rc. So why do you hand a thread an Arc and not an Rc?
Back to the workshop. A guard stands at the entrance to the shop floor and looks at every worker's pass. He will not accept a pass from the building next door, even if it looks exactly the same.
In Rust that guard is the compiler, and the "may enter the shop floor" mark is the Send trait.
Two marker traits
How does the compiler know that an Arc may go to a thread and an Rc may not? From two marker traits with no methods:
Send— a value can be moved to another thread;Sync— a value can be looked at from several threads through a shared reference.
thread::spawn requires everything the closure captured to be Send. Almost all types get these traits automatically: i32, String, Vec.
use std::sync::Arc;
use std::thread;
fn main() {
let s = Arc::new(String::from("hi"));
let h = thread::spawn(move || s.len());
println!("{}", h.join().unwrap()); // 2
}Let's go line by line:
Arc::newputs the string under a shared pass.movemovessinto the closure, andspawnchecks thatArc<String>isSend. The check passes.- The thread computes the string's length,
joinreturns it tomain, and2is printed.
Why Rc is not Send
Rc is an exception, and the reason is how the type works. The count in an Rc changes with ordinary, non-atomic operations: two threads that clone an Rc at the same moment can corrupt it. So Rc is not Send. The count in an Arc is atomic, and an Arc<Mutex<T>> can go to a thread.
The check happens at build time and costs nothing at run time.
Here the guard picture is inexact. A real guard looks at the pass every time someone walks up. The compiler checks the program once, before it runs, and there is no check left while it runs.
"How does Arc differ from Rc?" and "What do Send and Sync mean?" are common interview questions.
Common mistake
An Rc is used to give the thread one more owner:
use std::rc::Rc;
use std::thread;
fn main() {
let s = Rc::new(String::from("hi"));
let h = thread::spawn(move || s.len()); // ✗
println!("{}", h.join().unwrap());
}error[E0277]: `Rc<String>` cannot be sent between threads safelyThe program does not compile. move decides only how the closure captures s, while Send decides whether the value may go to another thread at all. The fix is Arc instead of Rc: use std::sync::Arc; and Arc::new(String::from("hi")).
Key points
Sendmeans a value can be moved to another thread;Syncmeans it can be looked at from several threads through a shared reference.spawnrequiresSend;Rcis notSendbecause its count is not atomic, and the compiler answers with error E0277.- A shared owner for threads comes from
Arc: its count is atomic.