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

#35 in Concurrency

Download history 1577066/week @ 2024-07-20 1578837/week @ 2024-07-27 1540839/week @ 2024-08-03 1603194/week @ 2024-08-10 1590385/week @ 2024-08-17 1613587/week @ 2024-08-24 1531171/week @ 2024-08-31 1609697/week @ 2024-09-07 1482087/week @ 2024-09-14 1770101/week @ 2024-09-21 1823843/week @ 2024-09-28 2308986/week @ 2024-10-05 2189514/week @ 2024-10-12 2290009/week @ 2024-10-19 1734697/week @ 2024-10-26 1748315/week @ 2024-11-02

8,251,711 downloads per month
Used in 19,887 crates (7 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");

lib.rs:

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