3 releases (breaking)

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

#657 in Filesystem

Download history 1434/week @ 2024-07-21 1310/week @ 2024-07-28 1414/week @ 2024-08-04 1094/week @ 2024-08-11 1004/week @ 2024-08-18 1467/week @ 2024-08-25 1081/week @ 2024-09-01 1253/week @ 2024-09-08 1628/week @ 2024-09-15 1939/week @ 2024-09-22 3041/week @ 2024-09-29 4558/week @ 2024-10-06 4322/week @ 2024-10-13 7426/week @ 2024-10-20 4894/week @ 2024-10-27 5364/week @ 2024-11-03

22,087 downloads per month
Used in 22 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