Skip to content
Guest
Rust · Course Syllabus Show lessons
Concurrency · 10 min read · Intermediate

Fearless Concurrency: Threads, Channels & Arc<Mutex<T>>

Use Send/Sync traits, std::thread, mpsc channels, and Arc<Mutex<T>> so data races are impossible in safe Rust.

What you'll learn

  • Spawn threads safely and join handles cleanly
  • Share state across threads with Arc<Mutex<T>>
  • Pass messages between threads with std::sync::mpsc channels

Overview

Use Send/Sync traits, std::thread, mpsc channels, and Arc<Mutex<T>> so data races are impossible in safe Rust.

Code Example

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let c = Arc::clone(&counter);
    let handle = thread::spawn(move || { *c.lock().unwrap() += 1; });
    handle.join().unwrap();
    println!("{}", *counter.lock().unwrap());
}

Key Takeaways

  • Spawn threads safely and join handles cleanly
  • Share state across threads with Arc<Mutex<T>>
  • Pass messages between threads with std::sync::mpsc channels

Quick Check

Check Your Understanding

Score: 0 / 1

1. Why does Rust require `Arc<T>` instead of `Rc<T>` when sharing ownership across multiple OS threads?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind