5个版本
0.1.4 | 2021年7月11日 |
---|---|
0.1.3 | 2021年3月12日 |
0.1.2 | 2021年2月21日 |
0.1.1 | 2021年2月14日 |
0.1.0 | 2021年2月14日 |
#832 in 异步
22KB
395 行
async-file-lock
支持自动锁定和自动查找的异步文件锁定。
功能
- 异步文件锁定(独占和共享)
- 在进行任何读取或写入操作前自动锁定
- 在进行任何读取或写入操作前自动查找
- 手动锁定/解锁
平台
async-file-lock 应该可以在支持 libc 的任何平台上运行。
示例
use async_file_lock::FileLock;
use tokio::io::{AsyncWriteExt, SeekFrom, AsyncSeekExt, AsyncReadExt};
//...
// Create file in read/write mode
let mut file = FileLock::create(&tmp_path).await?;
// Supports any methods from AsyncReadExt, AsyncWriteExt, AsyncSeekExt
// Locks exclusive
file.write(b"a").await?;
// Releases lock
file.seek(SeekFrom::Start(0)).await?;
let mut string = String::new();
// Locks shared
file.read_to_string(&mut string).await?;
// Releases lock
file.seek(SeekFrom::Start(0)).await?;
// Locks exclusive and holds
file.lock_exclusive().await?;
file.set_seeking_mode(SeekFrom::End(0));
// Seek to end and write
file.write(b"b").await?;
file.seek(SeekFrom::Start(0)).await?;
// Seek to end and write
file.write(b"c").await?;
// Finally releases lock
file.unlock().await;
file.lock_shared().await?;
// Cursor is at the end of a file, we want to read whole file.
file.seek(SeekFrom::Start(0)).await?;
// Removing seeking mode, otherwise before reading cursor will seek
// to the end of a file.
file.set_seeking_mode(SeekFrom::Current(0));
string.clear();
file.read_to_string(&mut string).await?;
assert_eq!(string, "abc");
依赖项
~4MB
~55K SLoC