Skip to content
Tutorials Center
My learning

Topics

Lesson 79 of 132 ยท Concurrency

Send, Sync and Fearless Concurrency

Understand Rust's Send and Sync marker traits: why Rc is not Send, why RefCell is not Sync, how the compiler rejects data races, and how to design thread-safe types.

In other languages, thread safety is a property you document and hope people respect: "this class is not thread-safe". In Rust it is a property the compiler checks. Every type either is or is not allowed to move between threads, and every type either is or is not allowed to be shared between threads. The compiler tracks this with two special traits, Send and Sync, and the functions that start threads demand them. That is the whole secret behind Rust's fearless concurrency: a data race is not something you avoid by discipline, it is something that does not compile.

This lesson explains what the two traits mean, why Rc, RefCell, Cell and MutexGuard are missing one or both, how to read the error messages you will meet, how to design your own thread-safe types, and the rare cases where you promise the compiler something with unsafe impl. It builds on Threads, Rc and Arc and Mutex and RwLock.

What Send and Sync mean

  • A type is Send if it is safe to move a value of that type to another thread (ownership transfer).
  • A type is Sync if it is safe to share it between threads by reference. Formally, T is Sync exactly when &T is Send.

They are marker traits: they have no methods. They are also auto traits: you never write impl Send for MyType. The compiler implements them automatically for a struct or enum when all of its fields are Send (or Sync), and withholds them as soon as one field is not. Primitive types, String, Vec<T> of sendable T, and so on are all Send and Sync with no effort from you.

You can ask the compiler directly with a function that only accepts the right types:

Rust Asking the compiler about Send and Sync

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The interesting pattern is that these checks cost nothing at run time. They are decided entirely during compilation, which also means that adding one non-Send field to a struct silently makes the whole struct non-Send.

The summary table

Type Send Sync Why
i32, bool, String, Vec<T> (T fine) yes yes Plain owned data
&T if T: Sync yes (if T: Sync) A shared reference is only as safe as its target
&mut T if T: Send if T: Sync Exclusive access moves with it
Rc<T> no no Its reference count is not atomic
Arc<T> if T: Send + Sync if T: Send + Sync Atomic count, but shared access to T needs both
Cell<T>, RefCell<T> if T: Send no Unsynchronized interior mutability
Mutex<T> if T: Send if T: Send The lock supplies the synchronization
RwLock<T> if T: Send if T: Send + Sync Many readers share &T
MutexGuard<T> no if T: Sync Some platforms require unlocking on the locking thread
*const T, *mut T no no Raw pointers: the compiler assumes the worst
mpsc::Sender<T> if T: Send yes (since 1.72) Cloneable handle
mpsc::Receiver<T> if T: Send no Only one consumer at a time

You do not need to memorize it. The pattern to remember is: non-atomic shared state is not Sync; non-atomic reference counts are not Send; locks and atomics turn unsafe-to-share things into safe-to-share things.

Why Rc is not Send

Rc<T> and Arc<T> do the same job, shared ownership with a reference count. The difference is that Rc updates its count with ordinary, cheap increments, and Arc uses atomic ones. If two threads cloned the same Rc at the same time, they could both read the count 1, both write 2, and the value would later be freed while still in use. So Rc simply is not Send, and the compiler turns the bug into an error:

Rust Rc cannot cross threads (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first line of the real message is:

TEXT
error[E0277]: `Rc<i32>` cannot be sent between threads safely

followed by a help line saying the trait `Send` is not implemented for `Rc<i32>` , and a note that the bound was "required by a bound in spawn". Read this error as a sentence: "thread::spawn requires its closure to be Send; the closure captures an Rc; Rc is not Send." The fix is to use Arc, which pays for atomic counting:

Rust Arc is the thread-safe Rc

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Why RefCell and Cell are not Sync

A RefCell checks borrow rules at run time using a plain counter. Two threads using the same RefCell at the same time could corrupt that counter, so RefCell<T> is not Sync: you may not share a reference to it across threads. It is Send (when T is): moving the whole thing to one other thread, where only that thread uses it, is fine.

Arc<RefCell<T>> is the classic wrong guess. Arc allows sharing, but Arc<T> is only Send when T is both Send and Sync:

Rust Arc of RefCell (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0277]: `RefCell<i32>` cannot be shared between threads safely
  = help: the trait `Sync` is not implemented for `RefCell<i32>`
  = note: required for `Arc<RefCell<i32>>` to implement `Send`

The compiler even adds a note recommending std::sync::RwLock for "aliasing and mutation between multiple threads". The rule of thumb, which you can check against the table above, is the thread-safe twin of every single-threaded type:

Single-threaded Multi-threaded
Rc<T> Arc<T>
RefCell<T> Mutex<T> or RwLock<T>
Cell<i32> AtomicI32
Rc<RefCell<T>> Arc<Mutex<T>>

Cell follows the same logic. Sharing one between two scoped threads fails with error[E0277]: `Cell<bool>` cannot be shared between threads safely and the note suggests AtomicBool.

Data races are compile errors

A data race needs three ingredients: two threads touch the same memory, at least one writes, and nothing orders them. Rust removes the combination with its borrowing rules: you can have many readers (&T) or one writer (&mut T), never both. Thread APIs extend the rule across threads.

Scoped threads show it clearly. Two threads that both mutate one local variable would be a race, and the borrow checker says no:

Rust Two scoped threads, one mutable variable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0499]: cannot borrow `count` as mutable more than once at a time

This is the same error you get from borrowing in single-threaded code, now guarding against a real race. The same thing happens with plain thread::spawn: the closure may outlive numbers (error[E0373]), and if you try to keep using numbers in the parent while the thread has it, you also get error[E0499]. And ownership closes the remaining gap: with move, the value belongs to exactly one thread.

To actually make two threads change a number, the type system forces you to name the synchronization:

Rust The fix: synchronization you can see

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Both Mutex<i32> and AtomicU32 are Sync, so &Mutex and &AtomicU32 can be shared by several threads. After the scope, we have exclusive ownership again, so into_inner gives the values without locking.

Rust prevents data races, not every concurrency bug. Deadlocks, logic races (check-then-act on separate locks), lost wake-ups and wrong ordering of messages are all still possible in safe Rust.

Why MutexGuard is not Send

MutexGuard is Sync when its data is, but not Send. On some operating systems a lock must be released by the same thread that took it, so moving a guard to another thread would be undefined behaviour. The compiler stops it:

Rust Sending a MutexGuard (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The message begins error[E0277]: `std::sync::MutexGuard<'_, i32>` cannot be sent between threads safely. The cure is to send the Arc and lock inside the new thread. The same error appears in async code when a guard is held across an .await in a task that must be Send; see Async/await Basics.

Designing thread-safe types

Most of the time you get thread safety for free by composing safe pieces. Say you want a shared statistics collector:

Rust A thread-safe type built from safe parts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The design principles that make this work:

  • Methods take &self. Interior synchronization (Mutex, atomics) lets many threads use the value without &mut.
  • Put the lock inside the type, so callers cannot forget it, and keep related fields under one lock.
  • Add a compile-time assertion like assert_thread_safe::<Stats>(). If someone later adds an Rc field, the build fails right there with a clear message, instead of far away in a spawn call.
  • Prefer owned, 'static data in anything handed to thread::spawn; use scoped threads for borrowed data.

Opting out and opting in

Because Send and Sync are auto traits, you can control them without code:

  • A type becomes !Send/!Sync automatically when it contains a raw pointer, Rc, Cell, and so on.
  • To make a type non-Send on purpose (for example a handle tied to one thread's resources), add PhantomData<*const ()> as a field.
Rust Opting out with PhantomData

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The other direction, opting in, is unsafe impl Send for MyType {}. It means "I, the programmer, promise this is safe even though the compiler cannot prove it". It is how the standard library itself makes Arc, Mutex and channels work, and how wrappers around C libraries declare that their handles are thread-safe. You must have a reason you can write down: a raw pointer to heap data that you exclusively own is Send; a pointer into data shared without synchronization is not.

An incorrect unsafe impl Send or Sync re-opens the door to data races, and no tool will warn you. Write the safety argument in a // SAFETY: comment, keep the unsafe code tiny, and test it under Miri or a thread sanitizer. See Unsafe Rust.

Send and Sync in function signatures

The standard library's thread entry points show the rules in action. In simplified form:

Rust
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,

The closure must be Send (it moves to the new thread), the return value must be Send (it travels back through join), and both must be 'static (own all their data). Scoped threads relax 'static but keep Send. A function that takes a reference to share across threads asks for &T where T: Sync. When you write a generic function that spawns threads, you will add these same bounds, and the compiler will tell you which one is missing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does it mean for a type to be Send?

    Send is about transferring ownership to another thread. Sharing by reference is Sync: T is Sync when &T is Send.
  2. 2. Why is Rc<T> not Send?

    Rc uses plain increments for speed. Arc uses atomic ones, which is why Arc can cross threads.
  3. 3. Why does Arc<RefCell<i32>> fail to compile in thread::spawn?

    Arc<T> is Send only if T is Send + Sync. RefCell is not Sync; use Arc<Mutex<T>> instead.
  4. 4. Which statement about auto traits is correct?

    The compiler derives Send and Sync structurally, and the checks are purely compile-time.
  5. 5. What does unsafe impl Send for MyHandle {} mean?

    unsafe impl shifts the proof obligation to you. A wrong promise can cause data races without any compiler warning.

Summary

  • Send means a value can move to another thread; Sync means &T can be shared between threads. Both are marker auto traits derived from a type's fields.
  • Rc is neither Send nor Sync (non-atomic count); RefCell and Cell are Send but not Sync; MutexGuard is not Send; raw pointers are neither.
  • Every single-threaded tool has a thread-safe twin: Rc to Arc, RefCell to Mutex or RwLock, Cell to atomics.
  • thread::spawn demands Send + 'static, so data races become compile errors (E0277, E0373, E0499), but deadlocks and logic races remain possible.
  • Design thread-safe types from safe pieces with &self methods, add fn assert<T: Send + Sync>() checks, and reserve unsafe impl Send/Sync for audited code.

Next: Parallel Patterns Without Libraries