commit | 67fd967596dfbd1619b8171f0d2112ef4a4316eb | [log] [tgz] |
---|---|---|
author | Viktoriia Kovalova <[email protected]> | Mon May 27 20:10:26 2024 +0000 |
committer | Viktoriia Kovalova <[email protected]> | Mon May 27 20:10:26 2024 +0000 |
tree | 8076e3d75a836de2bd2d336ecba4c97dff415aa8 | |
parent | 14027f77b92e84fc6207638628ff84d87137d9d6 [diff] |
Import 'try-lock' crate Request Document: go/android-rust-importing-crates For CL Reviewers: go/android3p#cl-review For Build Team: go/ab-third-party-imports Bug: http://b/339188364 Test: m libtry_lock && atest --host try-lock_test_src_lib Change-Id: Iab31dec9ca5b5bebee500a5aee21271656e96b11
A light-weight lock guarded by an atomic boolean.
Most efficient when contention is low, acquiring the lock is a single atomic swap, and releasing it just 1 more atomic swap.
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");