#lock #mutex #rwlock #locking

padlock

安全获取 RwLock/Mutex 锁

3 个不稳定版本

0.2.0 2020年5月4日
0.1.1-alpha2020年2月1日
0.1.0-alpha2020年1月28日

#32 in #rwlock

Download history 477/week @ 2024-03-13 437/week @ 2024-03-20 352/week @ 2024-03-27 429/week @ 2024-04-03 451/week @ 2024-04-10 431/week @ 2024-04-17 466/week @ 2024-04-24 403/week @ 2024-05-01 333/week @ 2024-05-08 402/week @ 2024-05-15 453/week @ 2024-05-22 310/week @ 2024-05-29 338/week @ 2024-06-05 273/week @ 2024-06-12 295/week @ 2024-06-19 270/week @ 2024-06-26

1,230 个月下载量
5 个crate中使用(通过 tray-item

MIT/Apache

9KB
96

密码锁

安全获取 RwLock/Mutex 锁,永远不用担心忘记释放它们!

CircleCI docs

许可证

MIT 或 Apache-2.0


lib.rs:

安全获取 MutexRwLock

本crate中的所有方法都会尝试锁定传入的Mutex或RwLock,如果锁定失败,将调用 spin_loop_hint 并再次尝试。这种做法称为 自旋锁

这意味着所有调用都会阻塞当前线程。

重要:在使用如 mutex_lock 的方法时,请记住,当lambda表达式执行完毕时,锁首先会被释放。

示例

 use std::{
     thread,
     sync::{Arc, Mutex},
     time::Duration
 };

 #[derive(Debug)]
 struct Person {
     age: u8,
     name: String
 }

 fn main() {

     let people = Arc::new(Mutex::new(Vec::<Person>::new()));
     let mut threads = Vec::<thread::JoinHandle<()>>::new();

     // Write in one thread
     let people_clone = Arc::clone(&people);
     threads.push(thread::spawn(move || {

         for i in 0..10 {

             padlock::mutex_lock(&people_clone, |lock| {

                 lock.push(Person {
                     age: i * 10,
                     name: format!("Name {}", i)
                 });

             });

             thread::sleep(Duration::from_millis(500));

         }

     }));

     // Read from another
     let people_clone = Arc::clone(&people);
     threads.push(thread::spawn(move || {

         for _ in 0..6 {

             padlock::mutex_lock(&people_clone, |lock| {

                 for person in lock {
                     println!("{:?}", person);
                 }

             });

             thread::sleep(Duration::from_secs(1));

         }

     }));

     for t in threads {
         t.join();
     }

 }

无运行时依赖