RwLock Guards Many Reads One Write

RwLock lets any number of readers hold guards together while writers exclude everyone; try_read fails while a write guard is alive.

RustData Integrity

Code

rustsnippet
25 lines
use std::sync::RwLock;

fn main() {
    let config = RwLock::new(String::from("v1"));

    // 多个读 guard 可以同时存在:read 只要求共享访问
    let r1 = config.read().unwrap();
    let r2 = config.read().unwrap();
    println!("readers see: {}, {}", r1, r2);
    drop((r1, r2)); // 读写互斥:写之前必须放掉全部读 guard

    // 写 guard 独占:任何新的 read 都会阻塞到它释放
    *config.write().unwrap() = "v2".to_string();

    // try_read 探测:写锁期间读失败,guard 释放后恢复
    let probing = {
        let guard = config.write().unwrap();
        let blocked = config.try_read().is_err();
        (guard, blocked)
    };
    println!("try_read while writing: {}", probing.1);
    drop(probing.0);

    println!("after update: {}", *config.read().unwrap());
}

What the code does

Count the function main as the entire surface area of RwLock Guards Many Reads One Write.

Using it

Running the file prints labeled results such as readers see:, try_read while writing:, after update: — each operation’s effect is visible in the output.

Key statements

let guard = config.write().unwrap();
let r1 = config.read().unwrap();
let r2 = config.read().unwrap();

Interactive Tools for This Topic

FAQ

What does RwLock Guards Many Reads One Write print when run?
Invoke the file as-is — the `readers see:`, `try_read while writing:`, `after update:` prefixes identify which step printed each line.