typestar

RwLock in Rust

Many readers or one writer: the right lock when reads dominate.

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

fn main() {
    let table = Arc::new(RwLock::new(vec!["basics".to_string()]));

    let writer = {
        let table = Arc::clone(&table);
        thread::spawn(move || {
            table.write().unwrap().push("errors".to_string());
        })
    };
    writer.join().unwrap();

    let readers: Vec<_> = (0..3)
        .map(|id| {
            let table = Arc::clone(&table);
            thread::spawn(move || {
                let tours = table.read().unwrap();
                println!("{id} sees {} tours", tours.len());
            })
        })
        .collect();

    for r in readers {
        r.join().unwrap();
    }
}

How it works

  1. read may be held by several threads at once.
  2. write waits for every reader to finish.
  3. Both return guards that release on drop.

Keywords and builtins used here

The run, in numbers

Lines
28
Characters to type
514
Tokens
195
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 111 seconds.

Type this snippet

Step 2 of 3 in Shared state, step 5 of 15 in Concurrency & async.

← Previous Next →