pub struct DirLock(/* private fields */);
Expand description
A simple file-system-based mutex.
When constructing a value of this type, a directory is created at the specified path.
If a directory already exists, the constructor waits until it’s removed.
Dropping a DirLock
removes the corresponding directory.
Since creating a directory if it does not exist is an atomic operation on most operating systems,
this can be used as a quick-and-dirty cross-process mutex.
To guard against processes exiting without properly removing the lock, a file containing the current process ID is created inside the lock. If no process with that ID exists, another process may claim the lock for itself. If the file does not exist, the constructor waits until it does (or until the directory is removed).
Of course, this is still not completely fail-proof since the user or other processes could mess with the lock directory.
This type is a RAII lock guard, but unlocking a directory lock uses I/O and can error, so it is recommended to call drop_async
.
Implementations§
Source§impl DirLock
impl DirLock
Sourcepub async fn new(path: impl AsRef<Path>) -> Result<Self, Error>
pub async fn new(path: impl AsRef<Path>) -> Result<Self, Error>
Acquires a directory lock at the given path, without blocking the thread.
See the type-level docs for details.
Sourcepub fn new_sync(path: &impl AsRef<Path>) -> Result<Self, Error>
pub fn new_sync(path: &impl AsRef<Path>) -> Result<Self, Error>
Blocks the current thread until the lock can be established.
Sourcepub async fn drop_async(self) -> Result<(), Error>
pub async fn drop_async(self) -> Result<(), Error>
Unlocks this lock without blocking the thread.