Concurrency

Concurrency in Rust is built from ownership, borrowing, and thread-safety traits: values either move between threads, are borrowed within a guaranteed scope, or are shared through explicit synchronization.

Concepts

  • Threads — operating-system threads, JoinHandle, joining, and scheduling boundaries.
  • Channels — message passing with std::sync::mpsc and ownership transfer.
  • Shared State with Mutex — serialized mutable access with Mutex<T> and guards.
  • Arc — atomic reference-counted shared ownership across threads.
  • Send and Sync — marker traits that encode whether values can cross or be shared across threads.
  • RwLock — many-reader or one-writer synchronization for read-heavy state.
  • Atomics — lock-free primitive synchronization and memory ordering.
  • Scoped Threads — borrowing local data across threads within thread::scope.
  • Condvar — block threads until a mutex-protected predicate changes.
  • OnceLock and LazyLock — one-time and first-use thread-safe initialization for shared values.
  • Barrier — rendezvous a fixed group of threads at phase boundaries.
  • thread_local! — per-OS-thread static storage via LocalKey.

Patterns

Antipatterns

Premature Arc Mutex · Holding Locks Across Await · Shared State in Async · Async Message Passing · Blocking in Async · Tasks and spawn

Sources