FAQ - Help and questions

How do C++ threads and mutexes map to Rust, and why does the compiler reject my data race?

#porting#cpp#concurrencypublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

In C++ a mutex sits beside the data it protects and nothing enforces the link. In Rust the Mutex owns the data, so it can only be reached by locking. Threads that borrow local variables must be scoped, or the data must be moved or shared with Arc. The compiler rejects unsynchronised sharing at compile time.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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":

src/main.rsrust
use std::thread;

fn main() {
    let mut count = 0;
    let h = thread::spawn(|| {
        count += 1;
    });
    count += 1;
    h.join().unwrap();
    println!("{count}");
}
text
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:

src/main.rsrust
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());
}
text
total letters: 19

The 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#

  1. For each std::mutex and the variables it protects, make one Mutex<Struct> holding all of those variables.
  2. For std::lock_guard, use the guard that lock() returns; it unlocks when it goes out of scope.
  3. For std::atomic<T>, use AtomicU64 and its relatives.
  4. For std::thread that borrows locals and is joined in the same function, use thread::scope. For detached or long-lived threads, move owned data in, or share it with Arc.
  5. For std::condition_variable, use Condvar; for queues between threads, mpsc channels (see the thread on callbacks).
  6. For parallel loops (OpenMP, std::for_each with execution policies), use the rayon crate; 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet