#spin-lock #semaphore #mutex #raspberry-pi #rwlock #ruspiro #data-access

无std ruspiro-lock

为Raspberry Pi提供跨核心使用的自旋锁、信号量和互斥数据访问

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 嵌入式开发

Download history 46/week @ 2024-03-11 34/week @ 2024-03-18 31/week @ 2024-03-25 95/week @ 2024-04-01 16/week @ 2024-04-08 27/week @ 2024-04-15 30/week @ 2024-04-22 33/week @ 2024-04-29 21/week @ 2024-05-06 31/week @ 2024-05-13 24/week @ 2024-05-20 36/week @ 2024-05-27 21/week @ 2024-06-03 19/week @ 2024-06-10 27/week @ 2024-06-17 25/week @ 2024-06-24

每月96次下载
用于 8 个crate(2 直接使用)

MIT/Apache

60KB
907 代码行

RusPiRo Lock crate

提供简单易用锁的API

  • Spinlock:阻塞锁
  • Semaphore:原子锁计数器,阻塞或非阻塞
  • Mutex:阻塞锁,确保对其内部内容的互斥访问
  • RWLock:阻塞锁,提供对其内部内容的多个不可变和独占可变访问

CI Latest Version Documentation License

用法

要使用此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-APACHEhttps://apache.ac.cn/licenses/LICENSE-2.0)或MIT(LICENSE-MIThttp://opensource.org/licenses/MIT)下许可。

无运行时依赖