3 releases (breaking)

0.3.0 Dec 31, 2020
0.2.0 Jul 14, 2020
0.1.0 Jul 14, 2020

#574 in Filesystem

Download history 1662/week @ 2024-07-04 1422/week @ 2024-07-11 1474/week @ 2024-07-18 1512/week @ 2024-07-25 1386/week @ 2024-08-01 1192/week @ 2024-08-08 994/week @ 2024-08-15 1378/week @ 2024-08-22 1156/week @ 2024-08-29 1113/week @ 2024-09-05 1592/week @ 2024-09-12 1494/week @ 2024-09-19 3071/week @ 2024-09-26 3869/week @ 2024-10-03 4419/week @ 2024-10-10 5473/week @ 2024-10-17

17,241 downloads per month
Used in 24 crates (8 directly)

MIT license

14KB
260 lines

advisory-lock-rs

A cross-platform advisory file lock in Rust.

For detailed documentation please visit docs.rs/advisory-locks.


lib.rs:

Advisory lock provides simple and convenient API for using file locks.

These are called advisory because they don't prevent other processes from accessing the files directly, bypassing the locks. However, if multiple processes agree on acquiring file locks, they should work as expected.

The main entity of the crate is AdvisoryFileLock which is effectively a RwLock but for File.

Example:

use std::fs::File;
use advisory_lock::{AdvisoryFileLock, FileLockMode, FileLockError};
#
#
// Create the file and obtain its exclusive advisory lock
let exclusive_file = File::create("foo.txt").unwrap();
exclusive_file.lock(FileLockMode::Exclusive)?;

let shared_file = File::open("foo.txt")?;

// Try to acquire the lock in non-blocking way
assert!(matches!(shared_file.try_lock(FileLockMode::Shared), Err(FileLockError::AlreadyLocked)));

exclusive_file.unlock()?;

shared_file.try_lock(FileLockMode::Shared).expect("Works, because the exclusive lock was released");

let shared_file_2 = File::open("foo.txt")?;

shared_file_2.lock(FileLockMode::Shared).expect("Should be fine to have multiple shared locks");

// Nope, now we have to wait until all shared locks are released...
assert!(matches!(exclusive_file.try_lock(FileLockMode::Exclusive), Err(FileLockError::AlreadyLocked)));

// We can unlock them explicitly and handle the potential error
shared_file.unlock()?;
// Or drop the lock, such that we `log::error!()` if it happens and discard it
drop(shared_file_2);

exclusive_file.lock(FileLockMode::Exclusive).expect("All other locks should have been released");
#

Dependencies

~185KB