3 releases (breaking)

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

#769 in Filesystem

Download history 1085/week @ 2023-12-10 978/week @ 2023-12-17 826/week @ 2023-12-24 1374/week @ 2023-12-31 1266/week @ 2024-01-07 1099/week @ 2024-01-14 1419/week @ 2024-01-21 1626/week @ 2024-01-28 1779/week @ 2024-02-04 1498/week @ 2024-02-11 1534/week @ 2024-02-18 1874/week @ 2024-02-25 1792/week @ 2024-03-03 1928/week @ 2024-03-10 2216/week @ 2024-03-17 1815/week @ 2024-03-24

7,909 downloads per month
Used in 18 crates (7 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