7 releases

Uses old Rust 2015

0.2.5 Dec 7, 2023
0.2.4 Jan 6, 2023
0.2.3 Jul 10, 2020
0.2.2 Jun 15, 2018
0.1.0 Mar 15, 2018

#56 in Concurrency

Download history 3340097/week @ 2025-09-23 3301001/week @ 2025-09-30 3272195/week @ 2025-10-07 3324762/week @ 2025-10-14 3537119/week @ 2025-10-21 3603306/week @ 2025-10-28 3559158/week @ 2025-11-04 3486093/week @ 2025-11-11 3649542/week @ 2025-11-18 2979009/week @ 2025-11-25 3605814/week @ 2025-12-02 4112310/week @ 2025-12-09 3982736/week @ 2025-12-16 2227019/week @ 2025-12-23 2458854/week @ 2025-12-30 4321127/week @ 2026-01-06

13,729,853 downloads per month
Used in 30,326 crates (8 directly)

MIT license

11KB
137 lines

TryLock

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.

Example

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");

No runtime deps