Module 12 · Concurrency & async
12.2Send & Sync
How Rust proves at compile time which values may move to another thread or be shared between threads, and how to pick the thread-safe version of a type.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| Knowing whether a type is safe to use from several threads | Rarely a question; each worker has its own objects | Read the docs ("not guaranteed to be thread-safe") | The compiler checks two traits: Send and Sync |
| Moving a value to another thread | postMessage copies it (structured clone) | Pass any object | Only if its type is Send |
| Sharing one value between threads | Only a SharedArrayBuffer | Share any object | Only if its type is Sync (then &T can cross threads) |
| Reference counting | Hidden; the GC tracks references | Hidden; the GC tracks references | Rc<T> on one thread, Arc<T> across threads |
| Changing data through a shared reference | Any object can be changed | Any object can be changed | Cell and RefCell on one thread; Mutex, RwLock or atomics across threads |
In TypeScript, you rarely have to ask whether an object is safe to use from two threads at once: each worker has its own objects, and anything you send is copied (or transferred, so the sender can’t use it anymore). The one exception, SharedArrayBuffer, holds only raw bytes.In C#, thread safety is a sentence in the documentation. List<T> and Dictionary<TKey, TValue> say their instance members aren’t guaranteed to be thread-safe; ConcurrentDictionary says it is. The compiler reads neither sentence, so using the wrong one from two threads compiles and fails at run time, some of the time. Rust writes thread safety into the type system with two traits, Send and Sync. Every value that crosses a thread boundary is checked against them at compile time. The previous lesson used them without naming them; this one shows how they work, and how they decide between Rc and Arc, or RefCell and Mutex.
Thread safety is part of the type
Here two threads each read a shared Settings value. The Rust version uses Rc<T>, the reference-counted pointer from Shared ownership, to share it, which is how you’d share it on one thread.
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
type Settings = { theme: string };
if (isMainThread) {
const settings: Settings = { theme: "dark" };
const lines = await Promise.all(
[0, 1].map(
(id) =>
new Promise<string>((resolve, reject) => {
// Each worker gets its own copy of settings.
const worker = new Worker(new URL(import.meta.url), { workerData: { id, settings } });
worker.once("message", resolve);
worker.once("error", reject);
}),
),
);
lines.forEach((line) => console.log(line));
} else {
const { id, settings } = workerData as { id: number; settings: Settings };
parentPort?.postMessage(`worker ${id} uses ${settings.theme}`);
}var settings = new Settings("dark");
// Both tasks share the same Settings object.
var tasks = Enumerable.Range(0, 2).Select(id => Task.Run(() => $"worker {id} uses {settings.Theme}"));
foreach (var line in await Task.WhenAll(tasks))
{
Console.WriteLine(line);
}
record Settings(string Theme);use std::rc::Rc;
use std::thread;
struct Settings {
theme: String,
}
fn main() {
let settings = Rc::new(Settings {
theme: String::from("dark"),
});
let handles: Vec<_> = (0..2)
.map(|id| {
let settings = Rc::clone(&settings);
thread::spawn(move || format!("worker {id} uses {}", settings.theme))
})
.collect();
for handle in handles {
println!("{}", handle.join().unwrap());
}
}Output of the TypeScriptC# version
worker 0 uses dark worker 1 uses dark
Rust doesn't compile this: error E0277
error[E0277]: `Rc<Settings>` cannot be sent between threads safely
--> settings.rs:15:27
|
15 | thread::spawn(move || format!("worker {id} uses {}", settings.theme))
| ------------- -------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| | |
| | `Rc<Settings>` cannot be sent between threads safely
| | within this `{closure@settings.rs:15:27: 15:34}`
| required by a bound introduced by this call
|
= help: within `{closure@settings.rs:15:27: 15:34}`, the trait `Send` is not implemented for `Rc<Settings>`
note: required because it's used within this closure
--> settings.rs:15:27
|
15 | thread::spawn(move || format!("worker {id} uses {}", settings.theme))
| ^^^^^^^
note: required by a bound in `spawn`The compiler refuses: Rc<Settings> cannot be sent between threads safely, because the trait Send isn’t implemented for it. Nothing in the program is racing yet. The problem is what could happen: Rc keeps its reference count in a plain integer, and if two threads cloned or dropped their Rcs at the same moment, their updates could overwrite each other. The count would go wrong, and the Settings could be freed while a thread still uses it.
The fix is one word. Arc<T> is the same pointer with an atomic count, which is safe to update from several threads:
use std::sync::Arc;
use std::thread;
struct Settings {
theme: String,
}
fn main() {
let settings = Arc::new(Settings {
theme: String::from("dark"),
});
let handles: Vec<_> = (0..2)
.map(|id| {
let settings = Arc::clone(&settings);
thread::spawn(move || format!("worker {id} uses {}", settings.theme))
})
.collect();
for handle in handles {
println!("{}", handle.join().unwrap());
}
}Output
worker 0 uses dark worker 1 uses dark
Why have Rc at all? Because atomic updates cost more than plain ones, and most shared data never leaves its thread. Rust lets you use the cheap one where it’s safe and makes it a compile error where it isn’t. C# has no such choice to make: the garbage collector tracks every object the same way, whichever threads use it.A garbage-collected runtime doesn’t offer that choice: it tracks every object the same way.
The two traits
thread::spawn is declared roughly like this:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
std::thread::spawn(f)
}The closure, and everything it captured, must be Send, and so must the value it returns. That bound is the whole mechanism: no special compiler rule for threads, just a trait bound like the ones in Generics & bounds.
Send: a value of this type can be moved to another thread. Most types areSend: numbers,String,Vec<T>, your own structs.Rc<T>isn’t.Sync: a value of this type can be shared between threads, used from several threads at once through&T. Precisely:TisSyncwhen&TisSend. Most types areSynctoo, because a&Tonly allows reading. The exceptions are types that allow changes through a shared reference without a lock, likeCell<T>andRefCell<T>.
They’re auto traits: you never write impl Send for Settings. The compiler implements them for a struct or enum automatically when all of its fields have them. Settings holds a String, which is Send and Sync, so Settings is both. Put an Rc in a field and the struct loses both. They’re also marker traits: they have no methods and nothing to call. They exist only to be checked.
You can ask the compiler about any type with two empty generic functions. This compiles, which proves every line:
use std::cell::RefCell;
use std::sync::{Arc, Mutex, RwLock};
fn is_send<T: Send>() {}
fn is_sync<T: Sync>() {}
fn main() {
is_send::<String>();
is_sync::<Vec<i32>>();
is_send::<Arc<String>>();
is_sync::<Arc<String>>();
is_send::<RefCell<i32>>(); // can move to another thread...
is_sync::<Mutex<RefCell<i32>>>(); // ...and a Mutex makes it shareable
is_sync::<RwLock<Vec<i32>>>();
println!("all checks passed");
}Output
all checks passed
Changing shared data: RefCell or Mutex
Here several threads add votes to one shared tally.
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
if (isMainThread) {
const batches = [["red", "blue"], ["blue", "green", "red"], ["blue"]];
// Workers can't share a Map, so only the main thread changes `tally`.
const tally = new Map<string, number>();
await Promise.all(
batches.map(
(batch) =>
new Promise<void>((resolve, reject) => {
const worker = new Worker(new URL(import.meta.url), { workerData: batch });
worker.once("message", (counts: Map<string, number>) => {
for (const [color, votes] of counts) {
tally.set(color, (tally.get(color) ?? 0) + votes);
}
resolve();
});
worker.once("error", reject);
}),
),
);
for (const [color, votes] of [...tally].sort(([a], [b]) => a.localeCompare(b))) {
console.log(`${color}: ${votes}`);
}
} else {
const counts = new Map<string, number>();
for (const color of workerData as string[]) {
counts.set(color, (counts.get(color) ?? 0) + 1);
}
parentPort?.postMessage(counts);
}using System.Collections.Concurrent;
string[][] batches = [["red", "blue"], ["blue", "green", "red"], ["blue"]];
// A plain Dictionary would compile here too; its docs say it isn't thread-safe.
var tally = new ConcurrentDictionary<string, int>();
Parallel.ForEach(batches, batch =>
{
foreach (var color in batch)
{
tally.AddOrUpdate(color, 1, (_, votes) => votes + 1);
}
});
foreach (var (color, votes) in tally.OrderBy(entry => entry.Key))
{
Console.WriteLine($"{color}: {votes}");
}use std::collections::HashMap;
use std::sync::Mutex;
use std::thread;
fn main() {
let batches: [&[&str]; 3] = [&["red", "blue"], &["blue", "green", "red"], &["blue"]];
let tally = Mutex::new(HashMap::new());
thread::scope(|s| {
for batch in batches {
let tally = &tally;
s.spawn(move || {
for color in batch {
*tally.lock().unwrap().entry(*color).or_insert(0) += 1;
}
});
}
});
let mut totals: Vec<_> = tally.into_inner().unwrap().into_iter().collect();
totals.sort();
for (color, votes) in totals {
println!("{color}: {votes}");
}
}Output
blue: 3 green: 1 red: 2
A plain HashMap is Send and Sync, but sharing one only gives each thread a &HashMap, which can’t insert anything. To change it through a shared reference you need interior mutability, and Rust has two families of it:
Cell<T>andRefCell<T>have no locking.Cellcopies values in and out;RefCellchecks borrows with a plain counter. They’reSend(you can move one to another thread) but notSync(two threads can’t use one at once): two threads setting aCelltogether would race, and two threads updating aRefCell’s counter together could both get a&mut.Mutex<T>,RwLock<T>and atomics do the same job with a lock or an atomic instruction, so they’reSync.Mutex<T>only needsTto beSend: since the lock lets one thread in at a time, the data never sees two threads at once. That’s howMutexturns aHashMap, or even aRefCell, into something threads can share.
Try RefCell here, as you would on one thread, and the compiler stops you:
use std::cell::RefCell;
use std::thread;
fn main() {
let visits = RefCell::new(0);
thread::scope(|s| {
s.spawn(|| *visits.borrow_mut() += 1);
s.spawn(|| *visits.borrow_mut() += 1);
});
println!("{}", visits.borrow());
}Rust doesn't compile this: error E0277
error[E0277]: `RefCell<i32>` cannot be shared between threads safely --> main.rs:7:17 | 7 | s.spawn(|| *visits.borrow_mut() += 1); | ----- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `RefCell<i32>` cannot be shared between threads safely | | | required by a bound introduced by this call | = help: the trait `Sync` is not implemented for `RefCell<i32>` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead = note: required for `&RefCell<i32>` to implement `Send` note: required because it's used within this closure --> main.rs:7:17 | 7 | s.spawn(|| *visits.borrow_mut() += 1); | ^^ note: required by a bound in `Scope::<'scope, 'env>::spawn`
The scoped thread’s closure holds a &RefCell<i32>, and &RefCell<i32> is only Send if RefCell<i32> is Sync, which it isn’t. The compiler’s note even suggests a thread-safe replacement, RwLock. Compare a Dictionary used from Parallel.ForEach: it compiles, and either corrupts its internal state or throws, depending on timing.In TypeScript the same mistake can’t be written, because the workers never see the same object; the price is copying the data or funneling every change through one thread.
Which one should I use?
Each tool for sharing comes in a single-thread version and a thread-safe version. Use the single-thread one unless the value crosses threads; the compiler tells you if it does.
| What | When | Why | How |
|---|---|---|---|
Rc<T> | Several owners of one value, all on one thread. | Cheapest shared ownership: the count is a plain integer. Not Send or Sync. | let a = Rc::new(value); let b = Rc::clone(&a); |
Arc<T> | Several owners on different threads (not needed with thread::scope). | Atomic count: safe across threads, slightly slower to clone and drop. Send and Sync when T is both. | let a = Arc::new(value); let b = Arc::clone(&a); |
Cell<T>, RefCell<T> | Changing a value through a shared reference on one thread. | No locking at all. Send but not Sync. | cell.set(1), refcell.borrow_mut().push(x) |
Mutex<T> | Threads change the same value. | One thread at a time; Sync whenever T is Send. | data.lock().unwrap() |
RwLock<T> | Threads mostly read the value and rarely change it. | Many readers at once. Needs T: Send + Sync to be Sync. | data.read().unwrap(), data.write().unwrap() |
Atomics (AtomicUsize, AtomicBool) | Threads share one counter or flag. | No lock, one instruction. | count.fetch_add(1, Ordering::Relaxed) |
The same choices as questions to ask in order:
Does the value stay on one thread?
YesNoUse
Rc<T>to share it andCell<T>orRefCell<T>to change itNo atomics, no locks. If it later has to cross threads, the compiler reports E0277 and you switch.Do the threads only read it?
YesNoBorrow it in
thread::scope, or share it withArc<T>Read-only data needs no lock:&Tcrosses threads wheneverTisSync.Is it a single number or flag?
YesNoUse an atomic:
AtomicUsize,AtomicU64,AtomicBoolPut it inArcfor spawned threads, or borrow it inthread::scope.Is it read far more often than it's changed?
YesNoUse
RwLock<T>Readers don't block each other; a writer waits for them.Otherwise: Use
Mutex<T>, insideArcfor spawned threads. Or pass the data through a channel instead of sharing it.
Rule of thumb: write single-threaded code with Rc and RefCell, and let the compiler tell you when a value crosses a thread boundary. Then reach for the thread-safe twin: Rc becomes Arc, and RefCell becomes Mutex (or RwLock, or an atomic for a single number).
Under the hood
Send and Sync cost nothing at run time. They’re checked during compilation and then disappear; there’s no flag stored in the value. The table below is what the standard library declares for the types you’ve met. “If” means the wrapper passes on whatever its contents have:
| Type | Send? | Sync? | Why |
|---|---|---|---|
i32, String, Vec<T>, HashMap<K, V> | Yes (if contents are) | Yes (if contents are) | Changes need &mut, which only one thread can hold. |
Rc<T> | No | No | Its count is updated without atomics. |
Arc<T> | If T: Send + Sync | If T: Send + Sync | Atomic count; every owner can reach &T from its own thread. |
Cell<T>, RefCell<T> | If T: Send | No | They change through & with no lock. |
Mutex<T> | If T: Send | If T: Send | One thread at a time. |
RwLock<T> | If T: Send | If T: Send + Sync | Several readers may hold &T at once. |
MutexGuard<'_, T> | No | If T: Sync | Some platforms require the thread that locked a mutex to unlock it. |
&T | If T: Sync | If T: Sync | Sending a &T shares the T. |
&mut T | If T: Send | If T: Sync | A &mut is exclusive, so sending it is like moving the T. |
*const T, *mut T | No | No | The compiler can’t know what a raw pointer points at. |
MutexGuard not being Send means a thread can’t lock a mutex and hand the locked guard to another thread. It matters most in async code, where a task can move between threads at every .await; the next lesson shows what that means for holding a lock across .await.
Raw pointers are the reason the auto traits can be trusted. Anything built on one, such as a type that manages its own memory, starts out neither Send nor Sync. If its author has checked that it really is safe to move between threads, they say so with an unsafe impl:
fn is_send<T: Send>() {}
struct Buffer {
ptr: *mut u8,
len: usize,
}
// SAFETY: Buffer is the only owner of the memory `ptr` points at,
// so moving it to another thread moves that memory with it.
unsafe impl Send for Buffer {}
fn main() {
is_send::<Buffer>();
println!("Buffer is Send");
}Output
Buffer is Send
unsafe here doesn’t switch the check off; it’s a promise the compiler can’t verify, which is why it needs the keyword. Vec<T>, Arc<T> and Mutex<T> are all built this way inside the standard library. In your own code you’ll almost never need it: a struct made of safe fields gets the right answer automatically. Unsafe & FFI covers unsafe properly.
Common pitfalls
Common pitfallOne field makes the whole type non-Send
Because the traits are derived from fields, an Rc buried anywhere inside a struct stops the whole struct from crossing threads, and the error appears where you spawn, not where you added the field:
use std::rc::Rc;
use std::thread;
struct Session {
user: Rc<String>,
}
fn greet(session: Session) {
println!("hello, {}", session.user);
}
fn main() {
let session = Session {
user: Rc::new(String::from("ada")),
};
let handle = thread::spawn(move || greet(session));
handle.join().unwrap();
}Rust doesn't compile this: error E0277
error[E0277]: `Rc<String>` cannot be sent between threads safely
--> main.rs:16:32
|
16 | let handle = thread::spawn(move || greet(session));
| ------------- -------^^^^^^^^^^^^^^^
| | |
| | `Rc<String>` cannot be sent between threads safely
| | within this `{closure@main.rs:16:32: 16:39}`
| required by a bound introduced by this call
|
= help: within `{closure@main.rs:16:32: 16:39}`, the trait `Send` is not implemented for `Rc<String>`
note: required because it appears within the type `Session`
--> main.rs:4:8
|
4 | struct Session {
| ^^^^^^^
note: required because it's used within this closure
--> main.rs:16:32
|
16 | let handle = thread::spawn(move || greet(session));
| ^^^^^^^
note: required by a bound in `spawn`Read the error’s notes: they name the type that isn’t Send and the struct it appears in. Change that field to Arc<String>, or to a plain String if it doesn’t need to be shared.
Common pitfallArc doesn't make the contents thread-safe
Arc<RefCell<T>> compiles, as long as it stays on one thread. The moment it crosses a thread boundary, you get E0277 for the RefCell, because an Arc gives every thread a shared reference to the same RefCell. Arc makes ownership thread-safe; for changes, the contents need their own synchronization. Use Arc<Mutex<T>>. (Clippy’s arc_with_non_send_sync lint warns about this early.)
Common pitfallDon't unsafe impl your way out of E0277
When the compiler says a type isn’t Send, adding unsafe impl Send makes the error go away and brings back exactly the data race it was preventing. An unsafe impl is a claim that you’ve checked what the compiler couldn’t, which is only true for types built on raw pointers that you manage yourself. For everything else, change the field types instead.
Try it yourself
Exercise: port this to Rust
Port this program to Rust. Three workers each build a label from shared, read-only settings and count themselves in a shared counter. Use scoped threads: you shouldn’t need Arc, Mutex or Rc.
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
type Settings = { prefix: string };
type Job = { id: number; settings: Settings; finished: Int32Array };
if (isMainThread) {
const settings: Settings = { prefix: "job" };
const finished = new Int32Array(new SharedArrayBuffer(4));
const labels = await Promise.all(
[0, 1, 2].map(
(id) =>
new Promise<string>((resolve, reject) => {
const job: Job = { id, settings, finished };
const worker = new Worker(new URL(import.meta.url), { workerData: job });
worker.once("message", resolve);
worker.once("error", reject);
}),
),
);
labels.forEach((label) => console.log(`${label} done`));
console.log(`${Atomics.load(finished, 0)} jobs finished`);
} else {
const { id, settings, finished } = workerData as Job;
Atomics.add(finished, 0, 1);
parentPort?.postMessage(`${settings.prefix}-${id}`);
}var settings = new Settings("job");
var finished = 0;
var labels = await Task.WhenAll(Enumerable.Range(0, 3).Select(id => Task.Run(() =>
{
Interlocked.Increment(ref finished);
return $"{settings.Prefix}-{id}";
})));
foreach (var label in labels)
{
Console.WriteLine($"{label} done");
}
Console.WriteLine($"{finished} jobs finished");
record Settings(string Prefix);Expected output
job-0 done job-1 done job-2 done 3 jobs finished
Show a hint
Use thread::scope. Inside it, make plain references let settings = &settings; and let finished = &finished; so each move closure copies the references, not the values. Settings and AtomicUsize are both Sync, so no Arc is needed.
Show a solution
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
struct Settings {
prefix: String,
}
fn main() {
let settings = Settings {
prefix: String::from("job"),
};
let finished = AtomicUsize::new(0);
let labels: Vec<String> = thread::scope(|s| {
let settings = &settings;
let finished = &finished;
let handles: Vec<_> = (0..3)
.map(|id| {
s.spawn(move || {
finished.fetch_add(1, Ordering::Relaxed);
format!("{}-{id}", settings.prefix)
})
})
.collect();
handles
.into_iter()
.map(|handle| handle.join().unwrap())
.collect()
});
for label in &labels {
println!("{label} done");
}
println!("{} jobs finished", finished.load(Ordering::Relaxed));
}A scoped thread can capture &Settings because Settings is Sync: it has only a String field. AtomicUsize is Sync too, and fetch_add changes it through a shared reference. Collecting the join results in spawn order keeps the labels in a fixed order, and the scope has joined every thread before finished is read.
Saved in this browser only.