Loading...
Start Coding

Rust Mutex and RwLock

Master Rust with Coddy

Learn Rust through interactive, bite-sized lessons. Master memory safety without garbage collection.

Start Rust Journey →

In Rust's concurrent programming model, Mutex and RwLock are essential synchronization primitives. They ensure safe access to shared data across multiple threads, preventing race conditions and data corruption.

Mutex (Mutual Exclusion)

A Mutex allows only one thread to access the data at a time. It's ideal for scenarios where you need exclusive access to a resource.

Basic Usage


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());
}
    

In this example, we use a Mutex to safely increment a counter across multiple threads.

RwLock (Read-Write Lock)

An RwLock allows multiple readers or a single writer to access the data. It's useful when you have data that is frequently read but infrequently modified.

Basic Usage


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

fn main() {
    let data = Arc::new(RwLock::new(vec![1, 2, 3]));
    let mut handles = vec![];

    // Reader threads
    for _ in 0..3 {
        let data = Arc::clone(&data);
        handles.push(thread::spawn(move || {
            let numbers = data.read().unwrap();
            println!("Read: {:?}", *numbers);
        }));
    }

    // Writer thread
    {
        let data = Arc::clone(&data);
        handles.push(thread::spawn(move || {
            let mut numbers = data.write().unwrap();
            numbers.push(4);
            println!("Write: {:?}", *numbers);
        }));
    }

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

This example demonstrates how RwLock allows multiple reader threads to access the data concurrently, while ensuring exclusive access for the writer thread.

Key Considerations

  • Use Mutex when you need exclusive access to data.
  • Prefer RwLock when you have mostly read operations and occasional writes.
  • Be cautious of deadlocks when using multiple locks.
  • Remember to release locks as soon as possible to improve concurrency.
  • Use Arc (Atomic Reference Counting) to share ownership across threads.

Related Concepts

To fully understand Mutex and RwLock in Rust, it's helpful to explore these related topics:

By mastering these synchronization primitives, you'll be well-equipped to write safe and efficient concurrent Rust programs.