14个版本
0.5.0 | 2021年12月25日 |
---|---|
0.4.2 | 2021年4月23日 |
0.4.1 | 2020年11月13日 |
0.3.3 | 2020年5月28日 |
0.0.2 | 2019年7月29日 |
#212 in 嵌入式开发
每月96次下载
用于 8 个crate(2 直接使用)
60KB
907 代码行
RusPiRo Lock crate
提供简单易用锁的API
Spinlock
:阻塞锁Semaphore
:原子锁计数器,阻塞或非阻塞Mutex
:阻塞锁,确保对其内部内容的互斥访问RWLock
:阻塞锁,提供对其内部内容的多个不可变和独占可变访问
用法
要使用此crate,只需将其依赖项添加到您的Cargo.toml
文件中
[dependencies]
ruspiro-lock = "0.5.0"
完成后,锁的定义和用法如下。请注意,为了在核心或线程之间共享这些锁原语,它们应被包装在Arc
中。
自旋锁
use ruspiro_lock::Spinlock;
fn main() {
let spin = Spinlock::new();
spin.aquire();
// following code is only executed if the lock could be aquired, the executing core pause till then
let _ = 10 + 3;
spin.release();
}
信号量
use ruspiro_lock::Semaphore;
fn main() {
let sema = Semaphore::new(1);
if sema.try_down().is_ok() {
// we gained access to the semaphore, do something
let _ = 20 /4;
sema.up();
}
}
互斥锁
use ruspiro_lock::Mutex;
fn main() {
let mutex = Mutex::new(0u32);
if let Some(mut data) = mutex.try_lock() {
*data = 20;
}
// once the data goes ot of scope the lock will be released
if let Some(data) = mutex.try_lock() {
println!("data: {}", *data);
// another lock should fail inside this scope
assert!(mutex.try_lock().is_none());
}
// a blocking lock on the data will block the current execution until
// the lock get's available
let mut data = mutex.lock();
*data = 12;
}
读写锁
use ruspiro_lock::RWLock;
fn main() {
let rwlock = Arc::new(RWLock::new(0u32));
let rwlock_clone = Arc::clone(&rwlock);
{
// try_lock and lock will provide a WriteLockGuard
let mut data = rwlock.lock();
*data = 20;
// if a write lock exists no other write or read lock's could be aquired
assert!(rwlock_clone.try_lock().is_none());
assert!(rwlock_clone.try_read().is_none());
}
{
// multiple read locks are possible
let data = rwlock.read();
// if a read lock exists other read lock's can be aquired, but no write lock
assert!(rwlock_clone.try_read().is_some());
assert!(rwlock_clone.try_lock().is_none());
println!("{}", *data);
}
}
许可证
根据您的选择,在Apache License,Version 2.0(LICENSE-APACHE或https://apache.ac.cn/licenses/LICENSE-2.0)或MIT(LICENSE-MIT或http://opensource.org/licenses/MIT)下许可。