feat: parking_lot

This commit is contained in:
2020-12-26 09:20:48 +08:00
parent 6843d69daf
commit e3ac142ead

View File

@@ -1,16 +1,38 @@
// use crossbeam::atomic::AtomicCell;
use crossbeam_channel::unbounded;
// use lock_api::Mutex;
// use std::sync::Arc;
use parking_lot::FairMutex;
use parking_lot::RwLock;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
fn main() {
// let lock = Arc::new(Mutex::new::<RawSpinlock, i32>(0_i32));
let mutex = Arc::new(FairMutex::new(0_i32));
let rw_lock = Arc::new(RwLock::new(0_i32));
// let cell = AtomicCell::new(0_i32);
let (s, r) = unbounded::<i32>();
let thead_mutex = mutex.clone();
let thread_rw_lock = rw_lock.clone();
thread::spawn(move || {
s.send(1).unwrap();
for i in 1..=10 {
thread::sleep(Duration::from_millis(500));
s.send(i).unwrap();
let mut m = thead_mutex.lock();
*m += 1;
let mut rw = thread_rw_lock.write();
*rw += 1;
}
s.send(-1).unwrap();
});
loop {
let x = r.recv().unwrap();
println!("Received: {}", x);
if x < 0 {
break;
}
println!("Received: {}, mutext: {}, rw_lock: {}", x, *mutex.lock(), *rw_lock.read());
}
}