Skip to main content
Module 10 · Lesson 4 of 424/24 in the course~22 min
Module lessons (4/4)

Shared State Arc<Mutex<T>> and Marker Trait Send/Sync

Lesson preview5 hands-on exercises readyCourse Rust · Module 10 — Advanced Traits and Fearless Concurrency

Combining Arc::clone and Mutex::lock() across multiple threads, preventing deadlocks, and understanding why Send/Sync eliminate data races at compile time.

What you'll learn in this lesson

  • Share mutable state between multiple threads safely by pairing Arc<T> and Mutex<T>.
  • Take advantage of the RAII guard MutexGuard to automatically unlock the mutex when exiting the scope.
  • Understand the role of the automatic trait markers Send and Sync in preventing compile-time data races.

Overview

When multiple workers need to update a common state (a counter, a cache, or a connection pool) instead of exchanging messages, in Rust you can't share a simple Rc<RefCell<T>>: the compiler rejects it because it's not thread-safe! The atomic pair Arc<Mutex<T>> is needed.

Almost all safe concurrency in Rust relies on two marker traits (traits without methods automatically inferred by the compiler):

Sections covered in this lesson

  1. 11. Why you need both: Arc<T> + Mutex<T>
  2. 22. The Trait Markers Send and Sync
  3. 33. Prevent Poisoning, Deadlock and Contention
  4. 4Practical exercises
  5. 5Check for understanding
Pro Lesson · Module 10 — Advanced Traits and Fearless Concurrency

Unlock "Shared State Arc<Mutex<T>> and Marker Trait Send/Sync" and the full Course Rust curriculum

Combining `Arc::clone` and `Mutex::lock()` across multiple threads, preventing deadlocks, and understanding why `Send`/`Sync` eliminate data races at compile time.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course Rust plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.