Debian Codegraph @

third_party/rust/try-lock/README.md

raw
1 # TryLock
2
3 - [Crates.io](https://crates.io/crates/try-lock)
4 - [Docs](https://docs.rs/try-lock)
5
6 A light-weight lock guarded by an atomic boolean.
7
8 Most efficient when contention is low, acquiring the lock is a single atomic swap, and releasing it just 1 more atomic swap.
9
10 ## Example
11
12 ```rust
13 use std::sync::Arc;
14 use try_lock::TryLock;
15
16 // a thing we want to share
17 struct Widget {
18 name: String,
19 }
20
21 // lock it up!
22 let widget1 = Arc::new(TryLock::new(Widget {
23 name: "Spanner".into(),
24 }));
25
26 let widget2 = widget1.clone();
27
28
29 // mutate the widget
30 let mut locked = widget1.try_lock().expect("example isn't locked yet");
31 locked.name.push_str(" Bundle");
32
33 // hands off, buddy
34 let not_locked = widget2.try_lock();
35 assert!(not_locked.is_none(), "widget1 has the lock");
36
37 // ok, you can have it
38 drop(locked);
39
40 let locked2 = widget2.try_lock().expect("widget1 lock is released");
41
42 assert_eq!(locked2.name, "Spanner Bundle");
43 ```
44