RRust By Example
advancedConcurrency

RwLock

Read-write lock for concurrent reads and exclusive writes.

RwLock

Read-write lock for concurrent reads and exclusive writes.

Difficulty

Advanced

Code

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

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

    // multiple readers
    for i in 0..3 {
        let data = Arc::clone(&data);
        handles.push(thread::spawn(move || {
            let r = data.read().unwrap();
            println!("reader {}: {:?}", i, *r);
        }));
    }

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

    for h in handles {
        h.join().unwrap();
    }
    println!("final: {:?}", *data.read().unwrap());
}

Explanation

RwLock allows concurrent reads or exclusive writes.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the concurrency category to build a complete understanding of this topic.

More Concurrency Examples