Let us look at some of best lock libraries in rust.
[lwpptoc]
(a). 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.
Step 1: Install it
Install by adding the following in your Cargo.toml
:
try-lock = "0.2.3"
Example
Here is an 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");
Reference
Read more here.
(b). fslock
An API to use files as a lock. Supports non-std crates by disabling feature
std
.
Types
Currently, only one type is provided: [LockFile
]. It does not destroy the file after closed and behaviour on locking different file handles owned by the same process is different between Unix and Windows, unless you activate the multilock
feature, which enables the open_excl
method that locks files per file descriptor/handle on all platforms.
Step 1: Install it
Install it by adding the following line in your Cargo.toml
:
fslock = "0.2.1"
Example
Here is an example:
use fslock::LockFile;
fn main() -> Result<(), fslock::Error> {
let mut file = LockFile::open("mylock")?;
file.lock()?;
do_stuff();
file.unlock()?;
Ok(())
}
Reference
Read more here.
(c). fd-lock
Advisory cross-platform file locks using file descriptors.
Note that advisory lock compliance is opt-in, and can freely be ignored by other parties. This means this crate should never be used for security purposes, but solely to coordinate file access.
Step 1: Install it
Add the following line in your Cargo.toml
:
fd-lock = "3.0.3"
Example
Here is an example:
use std::io::prelude::*;
use std::fs::File;
use fd_lock::RwLock;
// Lock a file and write to it.
let mut f = RwLock::new(File::open("foo.txt")?);
write!(f.write()?, "chashu cat")?;
// A lock can also be held across multiple operations.
let mut f = f.write()?;
write!(f, "nori cat")?;
write!(f, "bird!")?;
Reference
Read more here.
(d). async-lock
This library provides Async synchronization primitives.
This crate provides the following primitives:
Barrier
- enables tasks to synchronize all together at the same time.Mutex
- a mutual exclusion lock.RwLock
- a reader-writer lock, allowing any number of readers or a single writer.Semaphore
- limits the number of concurrent operations.
Install it
Install it by adding the following to your Cargo.toml
:
async-lock = "2.4.0"
Reference
Read more here.