Rust : RwLock读写锁

RwLock允许同一时间有多个读对象或只存在一个写对象。在多线程中,如果要多个读或多个写,需要Arc::RwLock 。

use std::thread;
use std::sync::{Arc, Mutex};
use std::time;
use std::collections::{HashMap};
use std::sync::RwLock;
#[macro_use]
extern crate lazy_static;

lazy_static! {
    static ref HASHMAP: HashMap = {
        let mut m = HashMap::new();
        m.insert(0, "foo".into());
        m.insert(1, "bar".into());
        m.insert(2, "baz".into());
        m
    };
}

fn main(){
    // 非全局式
    {
        let mut hp = HashMap::new();
        hp.insert("1".to_string(),1);
        let lock_1 = Arc::new(RwLock::new(hp));//多个线程读写
        {
            println!("single thread write =>");
            let mut w = lock_1.write().unwrap();
            (*w).insert("2".to_string(),2);
        }
        {
            println!(" single thread read =>");
            let r = lock_1.read().unwrap();
            println!("r:{:?} {:?}",1,*r);
        }
        {
            println!("multi  readers => ");
            for i in 0..10{
                let lock = lock_1.clone();
                thread::spawn(move ||{
                    let r = lock.read().unwrap();
                    println!("r:{:?} {:?}",i,*r);
                }); 
            } 
        }
        {
            println!("multi  writers => ");
            for i in 0..10{
                let lock = lock_1.clone();
                thread::spawn(move ||{
                    let mut _w = lock.write().unwrap();
                    (*_w).insert(i.to_string(),i*i);
                    println!(":{:?} {:?}",i,*_w);
                }); 
            } 

        }
    

    }
    println!("RwLock=> mode");
    //全局式

    {
        let lock_1 = RwLock::new(HASHMAP.clone());//一个写,多个读
        // .read(); .write()
        {
            println!("single thread write =>");
            let mut w = lock_1.write().unwrap();
            (*w).insert(2,"2".to_string());
            println!("*w =>{:?}",*w);
        }
        {
            println!(" single thread read =>");
            let r = lock_1.read().unwrap();
            println!("r:{:?} {:?}",1,r);
        }

    }

    std::thread::sleep(std::time::Duration::from_secs(100));    
}

你可能感兴趣的:(Rust)