Answer#
A C++ program declares std::mutex m; and int counter; as separate variables and relies on every programmer remembering to lock m before touching counter. Forgetting is legal C++ and a data race at run time. Rust puts the data inside the lock: Mutex<u64> holds the number, and lock() returns a guard that gives access for as long as it lives. There is no way to read the number without holding the lock.
The rules the compiler enforces are Send (a value may move to another thread) and Sync (a reference to it may be shared between threads). Rc is neither, Mutex<T> is both when T can be sent, and a plain &mut cannot be shared at all. A thread that borrows a local variable must be proven not to outlive it.
This is the straight port of "a thread changes a counter while the main thread also does":
use std::thread;
fn main() {
let mut count = 0;
let h = thread::spawn(|| {
count += 1;
});
count += 1;
h.join().unwrap();
println!("{count}");
}error[E0373]: closure may outlive the current function, but it borrows `count`, which is owned by the current function
--> src/main.rs:5:27
|
5 | let h = thread::spawn(|| {
| ^^ may outlive borrowed value `count`
6 | count += 1;
| ----- `count` is borrowed here
|
help: to force the closure to take ownership of `count` (and any other referenced variables), use the `move` keyword
|
5 | let h = thread::spawn(move || {
| ++++
error[E0503]: cannot use `count` because it was mutably borrowed
--> src/main.rs:8:5
|
8 | count += 1;
| ^^^^^^^^^^ use of borrowed `count`The message was shortened. There are two errors for the two problems: the thread may outlive the variable (E0373), and the main thread uses a variable that the other thread has borrowed mutably (E0503). Using move alone would not fix the second one, because the variable would be copied and the threads would no longer share it.
A correct version uses scoped threads, which are all joined before the scope ends, so they may borrow locals, and a Mutex that owns the number:
use std::sync::Mutex;
use std::thread;
fn main() {
let counter = Mutex::new(0u64);
let words = vec!["alpha", "beta", "gamma", "delta"];
// scoped threads may borrow local variables, because they are all joined before the scope ends
thread::scope(|s| {
for w in &words {
let counter = &counter;
s.spawn(move || {
*counter.lock().unwrap() += w.len() as u64;
});
}
});
println!("total letters: {}", counter.lock().unwrap());
}total letters: 19The result is the same on every run (5 + 4 + 5 + 5 letters). When threads must live longer than the function that starts them, thread::spawn needs data that is owned by the thread or shared with Arc (see the first example in the thread on why teams choose Rust).
How to do it#
- For each
std::mutexand the variables it protects, make oneMutex<Struct>holding all of those variables. - For
std::lock_guard, use the guard thatlock()returns; it unlocks when it goes out of scope. - For
std::atomic<T>, useAtomicU64and its relatives. - For
std::threadthat borrows locals and is joined in the same function, usethread::scope. For detached or long-lived threads, move owned data in, or share it withArc. - For
std::condition_variable, useCondvar; for queues between threads,mpscchannels (see the thread on callbacks). - For parallel loops (OpenMP,
std::for_eachwith execution policies), use therayoncrate; it was not run for this thread.
Common mistakes#
- Holding the guard longer than needed, for example across a sleep or a network call.
- Locking two mutexes in different orders in different threads. Rust does not prevent deadlock.
- Treating
lock().unwrap()as an error-handling style. It panics if another thread panicked while holding the lock (a "poisoned" mutex); decide what your program should do then.
Related questions#
Does Rust prevent all concurrency bugs?#
It prevents data races in safe code. It does not prevent deadlocks, wrong ordering of operations, or logic errors.
Where is std::shared_mutex?#
RwLock<T>: many readers or one writer.
Sources#
- The Rust Book, "Shared-State Concurrency": https://doc.rust-lang.org/book/ch16-03-shared-state.html
std::thread::scope: https://doc.rust-lang.org/std/thread/fn.scope.html