Learn Rust · 12/14

Fearless Concurrency

10 min read

Welcome, brave Rustacean, to the realm of Fearless Concurrency! If you've ever tried to juggle tasks in your code, you know it can feel like trying to teach a cat to play the piano. But fear not! Rust's powerful and, dare we say, friendly concurrency features are here to turn that chaotic symphony into a harmonious masterpiece.

So, what is concurrency? In simple terms, it's the ability of different parts of a program to be executed out-of-order or in partial order, without affecting the final outcome. This is different from parallelism, where tasks literally run at the same time (e.g., on different CPU cores). Think of a chef in a kitchen: they might be chopping vegetables while also keeping an eye on something in the oven. That's concurrency. If they had another chef helping them, that would be parallelism.

The big, scary monster in the world of concurrency is the "data race." This happens when multiple parts of your code try to access the same data at the same time, and at least one of them is trying to write to it. This can lead to unpredictable behavior and bugs that are notoriously hard to track down. Rust's ownership system is the superhero that swoops in to prevent these data races at compile time. This is what makes Rust's concurrency "fearless."

Let's dive in and see how you can write concurrent code without pulling your hair out.


Spawning Threads to Run Code Simultaneously 🧵

The Definition: A thread is the smallest sequence of programmed instructions that can be managed independently by a scheduler. Think of your program as a single road. Spawning a new thread is like opening up a new lane, allowing traffic (your code) to flow simultaneously.

The Problem: Imagine you have a task that takes a long time to complete, like downloading a large file or processing a huge amount of data. If you run this on your main thread, your entire application will freeze until it's done. Nobody likes a frozen app! It's like waiting for a sloth to win a marathon.

The Solution: By spawning a new thread, you can offload the time-consuming task to run in the background, keeping your main application responsive.

In Rust, you can create a new thread using the thread::spawn function from the standard library.

rust
use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }

    handle.join().unwrap();
}

What's Happening Here?

  1. We use the necessary std::thread and std::time::Duration modules.
  2. thread::spawn takes a closure (an anonymous function) containing the code we want to run in the new thread.
  3. The main thread continues its execution in the second for loop.
  4. You'll notice the output from both threads is interleaved. This is because the operating system is switching between the threads.
  5. thread::spawn returns a JoinHandle. We can call the join method on this handle to wait for the spawned thread to finish its execution before the main function ends. If we didn't do this, the main thread would finish, and the program would exit, potentially killing the spawned thread before it's done.

Under the Hood: When you call thread::spawn, you are asking the operating system to create a new thread of execution. The OS scheduler then manages running this thread alongside your main thread, switching between them rapidly to give the illusion of simultaneous execution.

A Fun Fact: The term "thread" in computing is short for a "thread of execution." It's a way of representing the path your program takes as it runs.


Message Passing: Transferring Data Between Threads (Channels)

The Definition: Message passing is a technique for communication between threads where data is sent from one thread to another without being shared. One thread sends a message, and another thread receives it.

The Problem: Okay, so we have multiple threads running. That's great! But what if they need to talk to each other? For instance, what if our background thread, after downloading that huge file, needs to tell the main thread that the download is complete and here's the data? Trying to share data directly can lead to those dreaded data races we talked about.

The Solution: Rust provides "channels" for this purpose. A channel is a one-way communication conduit with a transmitter (the sending end) and a receiver (the receiving end). You can send data through the transmitter, and it will be picked up by the receiver on another thread. This is a very safe way to communicate because the ownership of the data is transferred along with the message.

Let's see it in action:

rust
use std::sync::mpsc; // mpsc stands for multiple producer, single consumer
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi from the spawned thread");
        tx.send(val).unwrap();
    });

    let received = rx.recv().unwrap();
    println!("Got: {}", received);
}

Breaking it Down:

  1. We create a new channel using mpsc::channel(). This function returns a tuple: the first element is the transmitter (tx), and the second is the receiver (rx).
  2. We move the transmitter (tx) into the spawned thread. The move keyword forces the closure to take ownership of the values it's using from the environment.
  3. Inside the spawned thread, we send a String message using tx.send(val). The send method takes ownership of val, so we can't use it again in the spawned thread after sending it.
  4. In the main thread, we call rx.recv(). This is a blocking method, which means the main thread will wait here until a message arrives in the channel.
  5. Once the message is received, it's printed to the console.

Under the Hood: A channel is essentially a queue that synchronizes access between threads. When you send a message, it gets pushed onto the queue. When you receive a message, it's popped off the queue. This ensures that data is transferred in an orderly and safe manner.


Shared-State Concurrency: Mutexes and Arc

The Definition: Shared-state concurrency is a concurrency model where multiple threads have access to the same shared data.

The Problem: Sometimes, message passing isn't the right fit. You might have a situation where multiple threads need to access and modify the same piece of data. Imagine two threads trying to update a counter at the same time. Thread A reads the value (let's say it's 5), adds 1 to it, and gets 6. But before it can write the 6 back, Thread B reads the original value (still 5), adds 1 to it, and writes back 6. Both threads ran, but the counter is only 6 instead of the expected 7. This is a classic race condition.

The Solution: To prevent this, we need a way to ensure that only one thread can access the data at a time. This is called "mutual exclusion," and in Rust, we achieve this using a Mutex (short for mutual exclusion).

A Mutex<T> provides a locking mechanism. Before a thread can use the data, it must acquire the lock. When it's done, it releases the lock, allowing another thread to acquire it.

rust
use std::sync::Mutex;
use std::thread;

fn main() {
    let counter = Mutex::new(0);
    let mut handles = vec![];

    for _ in 0..10 {
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
}

Wait, this code won't compile! The compiler will complain that counter is moved in the first iteration of the loop. This is because thread::spawn takes ownership of the environment it captures. We need a way to have multiple owners.

Enter Arc<T>: Arc stands for "Atomically Reference Counted." It's a smart pointer that lets us have multiple owners of a piece of data. It keeps track of how many references there are to the data, and when the last reference goes away, the data is cleaned up.

Let's fix our example using Arc<Mutex<T>>:

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

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
}

How it Works Now:

  1. We wrap our Mutex<i32> in an Arc.
  2. Inside the loop, we call Arc::clone(&counter) to create a new reference to the Arc. This increases the reference count.
  3. We move the cloned Arc into the new thread.
  4. Inside the thread, we call counter.lock() to acquire the lock on the Mutex. This returns a MutexGuard, which is a smart pointer that dereferences to our data.
  5. When the MutexGuard goes out of scope at the end of the closure, the lock is automatically released.
  6. The final println! also needs to lock the mutex to safely read the final value.

A Real-World Scenario: Imagine a single-person restroom in a busy cafe. The Mutex is the lock on the door. To use the restroom (access the data), a person (thread) must first lock the door. While it's locked, no one else can enter. When they are done, they unlock the door, allowing the next person in line to use it. Arc is like having a keycard system where multiple people have a copy of the keycard to access the restroom, but only one can be inside at a time.


Sync and Send Traits: Extensible Concurrency

The Definition: Send and Sync are two special "marker" traits in Rust that are crucial for thread safety. They don't have any methods; their only purpose is to signal to the compiler that a type has certain properties.

The Problem: How does Rust know what types can be safely sent between threads or shared between them? If we could send just any type across threads, we could easily introduce data races and other concurrency bugs. For example, a raw pointer is not safe to send to another thread because it doesn't have any concept of ownership or lifetime.

The Solution: The Send and Sync traits allow us to encode the thread-safety rules of our types directly into the type system.

  • Send Trait: A type is Send if it is safe to transfer ownership of it to another thread. Most primitive types like i32, bool, and String are Send. A type composed entirely of Send types is also Send.
  • Sync Trait: A type is Sync if it is safe to be shared between multiple threads (i.e., it's safe to have a &T shared across threads). If a type T is Sync, then &T is Send.

Most types in Rust are Send and Sync automatically. The compiler is smart enough to figure this out.

Why is this important for you?
You generally don't need to implement these traits yourself. However, understanding them helps you reason about why certain code might not compile. For example, the compiler will prevent you from using a type that is not Send in thread::spawn, or a type that is not Sync within an Arc.

This is the cornerstone of Rust's "fearless concurrency." The compiler enforces these rules for you, so you can be confident that your multi-threaded code is free from certain classes of bugs.

A Funny Exaggeration: Think of the Send and Sync traits as a bouncer at a very exclusive nightclub for threads. If a type doesn't have the Send or Sync VIP pass, the bouncer (the Rust compiler) says, "Sorry, you're not on the list," and refuses to let it in, preventing a potential brawl (data race) inside.


Further Reading and References

Challenge

Task: Multi-threaded Shared-State Counter

You are to build a Rust program that demonstrates shared-state concurrency. The goal is to have multiple threads concurrently increment a single shared counter and prove that the final count is correct.

Requirements:

  1. Create a shared integer counter that is safe to be accessed and modified by multiple threads. Wrap this counter in Arc and Mutex.
  2. Spawn exactly 10 threads.
  3. Inside each thread, implement a loop that increments the shared counter 50 times. You must acquire a lock on the Mutex for each increment.
  4. The main thread must store the JoinHandle for each spawned thread.
  5. After spawning all threads, the main thread must wait for all of them to complete their execution by calling join() on each handle.
  6. Once all threads have finished, the main thread should lock the counter one last time and print its final value.

Expected result

Your code must compile successfully. The program should create a shared counter, spawn 10 threads which each increment the counter 50 times, and then wait for all threads to complete. The final output printed to the console must be the total value of the counter, which should be 500. The implementation must correctly use Arc, Mutex, and thread::spawn to manage concurrent access and execution.

rust

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.