pub struct Spinlock<T: ?Sized> {
pub data: UnsafeCell<T>,
/* private fields */
}
Expand description
自旋锁结构体
Fields§
§data: UnsafeCell<T>
用户数据
Implementations§
source§impl<T: ?Sized> Spinlock<T>
impl<T: ?Sized> Spinlock<T>
sourcepub fn lock(&self, mode: SpinlockMode) -> SpinlockGuard<'_, T>
pub fn lock(&self, mode: SpinlockMode) -> SpinlockGuard<'_, T>
获取自旋锁,若线程无法获取自旋锁,就阻塞等待,直到能获得锁为止
- 若成功获取自旋锁,将返回 RAII Guard :
SpinlockGuard
,用于提供 Scoped Lock 机制。SpinlockGuard
中包含Spinlock
的引用, 当SpinlockGuard
生命周期结束时,会在drop()
方法中自动解锁自旋锁。
- 若失败,将返回错误码
SpinlockError
。
§参数说明
- mode: 锁模式
SpinlockMode::Lock
关闭抢占SpinlockMode::LockBh
关闭抢占、中断底半部SpinlockMode::LockCpuirq
关闭抢占、中断底半部和中断SpinlockMode::LockCpuirqSave(None)
关闭抢占、中断底半部和中断,并保存之前的中断标志
§示例
use xwrust::xwos::lock::spinlock::*;
static GLOBAL_SPINLOCK: Spinlock<u32> = Spinlock::new(0);
pub fn xwrust_example_spinlock() {
// ...省略...
let mut guard = GLOBAL_SPINLOCK.lock();
*guard = 1; // 访问共享变量
drop(guard); // 解锁
}
sourcepub fn trylock(
&self,
mode: SpinlockMode,
) -> Result<SpinlockGuard<'_, T>, SpinlockError>
pub fn trylock( &self, mode: SpinlockMode, ) -> Result<SpinlockGuard<'_, T>, SpinlockError>
尝试获取自旋锁,若线程无法获取自旋锁,立即返回错误
- 若成功获取自旋锁,将返回 RAII Guard :
SpinlockGuard
,用于提供 Scoped Lock 机制。SpinlockGuard
中包含Spinlock
的引用, 当SpinlockGuard
生命周期结束时,会在drop()
方法中自动解锁自旋锁。
- 若失败,将返回错误码
SpinlockError
。
§参数说明
- mode: 锁模式
SpinlockMode::Lock
关闭抢占SpinlockMode::LockBh
关闭抢占、中断底半部SpinlockMode::LockCpuirq
关闭抢占、中断底半部和中断SpinlockMode::LockCpuirqSave(None)
关闭抢占、中断底半部和中断,并保存之前的中断标志
§错误码
SpinlockError::Again
尝试获取锁失败
§示例
use xwrust::xwos::lock::spinlock::*;
static GLOBAL_SPINLOCK: Spinlock<u32> = Spinlock::new(0);
pub fn xwrust_example_spinlock() {
// ...省略...
match GLOBAL_SPINLOCK.trylock() {
Ok(mut guard) => { // 上锁成功
*guard = 1; // 访问共享变量
} // guard 生命周期结束,自动解锁
Err(e) => {
// 上锁失败
}
}
}
sourcepub fn unlock(guard: SpinlockGuard<'_, T>)
pub fn unlock(guard: SpinlockGuard<'_, T>)
解锁自旋锁,并释放 SpinlockGuard
§示例
use xwrust::xwos::lock::spinlock::*;
static GLOBAL_SPINLOCK: Spinlock<u32> = Spinlock::new(0);
pub fn xwrust_example_spinlock() {
// ...省略...
let mut guard = GLOBAL_SPINLOCK.lock();
*guard = 1; // 访问共享变量
Spinlock::unlock(guard); // 主动解锁
}