7 个版本
使用旧的 Rust 2015
0.2.5 | 2023 年 12 月 7 日 |
---|---|
0.2.4 | 2023 年 1 月 6 日 |
0.2.3 | 2020 年 7 月 10 日 |
0.2.2 | 2018 年 6 月 15 日 |
0.1.0 | 2018 年 3 月 15 日 |
#31 in 并发
6,237,324 每月下载量
在 18,607 个 Crates (直接使用 7 个) 中使用
11KB
137 代码行
TryLock
由原子布尔值保护的轻量级锁。
当竞争较低时效率最高,获取锁是单个原子交换,释放锁只需再进行一次原子交换。
示例
use std::sync::Arc;
use try_lock::TryLock;
// a thing we want to share
struct Widget {
name: String,
}
// lock it up!
let widget1 = Arc::new(TryLock::new(Widget {
name: "Spanner".into(),
}));
let widget2 = widget1.clone();
// mutate the widget
let mut locked = widget1.try_lock().expect("example isn't locked yet");
locked.name.push_str(" Bundle");
// hands off, buddy
let not_locked = widget2.try_lock();
assert!(not_locked.is_none(), "widget1 has the lock");
// ok, you can have it
drop(locked);
let locked2 = widget2.try_lock().expect("widget1 lock is released");
assert_eq!(locked2.name, "Spanner Bundle");
lib.rs
:
由原子布尔值保护的轻量级锁。
当竞争较低时效率最高,获取锁是单个原子交换,释放锁只需再进行一次原子交换。
示例
use std::sync::Arc;
use try_lock::TryLock;
// a thing we want to share
struct Widget {
name: String,
}
// lock it up!
let widget1 = Arc::new(TryLock::new(Widget {
name: "Spanner".into(),
}));
let widget2 = widget1.clone();
// mutate the widget
let mut locked = widget1.try_lock().expect("example isn't locked yet");
locked.name.push_str(" Bundle");
// hands off, buddy
let not_locked = widget2.try_lock();
assert!(not_locked.is_none(), "widget1 has the lock");
// ok, you can have it
drop(locked);
let locked2 = widget2.try_lock().expect("widget1 lock is released");
assert_eq!(locked2.name, "Spanner Bundle");