[][src]Crate advisory_lock

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");

Enums

FileLockError

An enumeration of possible errors which can occur while trying to acquire a lock.

FileLockMode

An enumeration of types which represents how to acquire an advisory lock.

Traits

AdvisoryFileLock

An advisory lock for files.