BorrowCheck › Rust language core

Concurrency

Threads, Send / Sync, channels, Mutex / RwLock, atomics and memory ordering, data races.

The topic explains concurrency in Rust and how the type system rules out data races. The questions on threads check why a thread::spawn closure must own its data (E0373), what join returns, and how scoped threads from thread::scope borrow local data and report a panic. The Send and Sync subtopic covers these auto traits on standard library types, Rc and RefCell across threads, a lock guard and ways to make a type not Send; the subtopic on mpsc channels covers message order, a closed channel, a zero-capacity channel and try_send. The subtopics on Mutex and RwLock deal with Arc<Mutex<T>>, re-locking and deadlock, poisoning after a panic, and Condvar::wait; the atomics subtopic covers fetch_add, compare_exchange and compare_exchange_weak, and memory ordering from Relaxed to SeqCst with the happens-before relation. The last subtopic separates a data race, which is undefined behavior, from a race condition, which safe code does not prevent, and shows what unsafe lets through. The topic builds on smart pointers and interior mutability and prepares for async.

46 questions: 19 basic, 23 intermediate, 4 advanced. 6 info pages, 22 sources.

Subtopics

  1. Threads and thread::scope
  2. Send and Sync
  3. Channels
  4. Mutex, RwLock, poisoning
  5. Atomics and memory ordering
  6. Data races and UB

Previous: Drop, RAII, drop order · Next: Async