`Send` and `Sync`
Send means a value can move to another thread. Sync means a shared reference can. The compiler implements both automatically unless a field forbids it.
Detailed Explanation
Send and Sync are auto traits and unsafe to implement by hand. A type is Send if all its fields are Send. It is Sync if &T is Send — that is, if sharing a read-only reference with another thread is safe. i32 is both. String is both. Rc<T> is neither. RefCell<T> is Send if T is, and never Sync. Mutex<T> is Sync if T is Send, which is the whole point of a mutex.
These traits are bounds on thread::spawn, on Arc::clone across threads, on Tokio tasks, on channels. spawn wants F: Send + 'static. Arc<T> is Send and Sync only when T is Send and Sync. That is why Arc<RefCell<T>> will not go to another thread and Arc<Mutex<T>> will.
You almost never write unsafe impl Send. If the compiler says a type is not Send, there is a Rc, a raw pointer, or a thread-local handle inside. Fix the type. An unsafe impl that is wrong is a data race the compiler will not catch, which is undefined behaviour.
Sync is about shared references, not about mutation. A Mutex<T> is Sync so that &Mutex<T> can be used from two threads; the mutex then hands out a MutexGuard that is the exclusive write. A type with an unsynchronised UnsafeCell is not Sync.
When you name these traits: API bounds (T: Send), reading a compiler error after spawn, or wrapping a type that contains a raw pointer. When you unsafe impl: almost never, and only if you can state why the raw pointer is still safe to move or share.
Code Examples
fn needs_send<T: Send>(_: T) {}
fn needs_sync<T: Sync>(_: &T) {}
fn main() {
needs_send(String::from("ada"));
needs_sync(&17);
// needs_send(std::rc::Rc::new(1)); // does not compile: Rc is not Send
println!("ok");
}Common Gotchas
`Rc` is not `Send` or `Sync`
The refcount is not atomic. Use `Arc` to share across threads.
`RefCell` is not `Sync`
Runtime borrow checking is not atomic. Use `Mutex` or `RwLock`.
`unsafe impl Send` is a soundness claim
A raw pointer field suppresses the auto trait on purpose. Putting the impl back without a lock is a data race.