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

#34 in Concurrency

Download history 1567446/week @ 2024-08-13 1603886/week @ 2024-08-20 1525017/week @ 2024-08-27 1640025/week @ 2024-09-03 1580367/week @ 2024-09-10 1640563/week @ 2024-09-17 1751019/week @ 2024-09-24 2132106/week @ 2024-10-01 2310391/week @ 2024-10-08 2266571/week @ 2024-10-15 1847392/week @ 2024-10-22 1708246/week @ 2024-10-29 1700267/week @ 2024-11-05 1760258/week @ 2024-11-12 1757239/week @ 2024-11-19 1212428/week @ 2024-11-26

6,743,122 downloads per month
Used in 20,177 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