3 个版本 (破坏性)

0.3.0 2020 年 12 月 31 日
0.2.0 2020 年 7 月 14 日
0.1.0 2020 年 7 月 14 日

#804文件系统

Download history 2038/week @ 2024-03-14 1981/week @ 2024-03-21 1760/week @ 2024-03-28 2756/week @ 2024-04-04 2599/week @ 2024-04-11 2695/week @ 2024-04-18 1430/week @ 2024-04-25 1198/week @ 2024-05-02 1444/week @ 2024-05-09 1472/week @ 2024-05-16 1439/week @ 2024-05-23 1237/week @ 2024-05-30 1334/week @ 2024-06-06 1582/week @ 2024-06-13 1629/week @ 2024-06-20 1481/week @ 2024-06-27

6,269 每月下载量
19 个 Crates 中使用 (直接使用 7 个)

MIT 许可证

14KB
260

advisory-lock-rs

Rust 的跨平台建议性文件锁。

有关详细文档,请访问 docs.rs/advisory-locks


lib.rs:

建议锁提供用于使用文件锁的简单且方便的 API。

之所以称为建议性,是因为它们不会阻止其他进程直接访问文件,绕过锁。然而,如果多个进程同意获取文件锁,则它们应按预期工作。

该库的主要实体是 AdvisoryFileLock,它实际上是一个 RwLock,但用于 File

示例

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

依赖项

~185KB