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

fn main() {
    let counter = Arc::new(RwLock::new(0));
    let mut readers = vec![];
    for turn in 0..3 {
        let counter_clone = Arc::clone(&counter);
        readers.push(thread::spawn(move || {
            thread::sleep(std::time::Duration::from_millis(turn * 500));
            let read_guard = counter_clone.read().unwrap();
            thread::sleep(std::time::Duration::from_millis(500));
            println!("reader{}: {}", turn, *read_guard);
        }));
    }
    let counter_clone = Arc::clone(&counter);
    let writer = thread::spawn(move || {
        let mut write_guard = counter_clone.write().unwrap();
        thread::sleep(std::time::Duration::from_secs(1));
        *write_guard += 1;
        println!("writer: {}", *write_guard);
    });
    for reader in readers {
        reader.join().unwrap();
    }
    writer.join().unwrap();
}