SpinLock

Struct SpinLock 

Source
pub struct SpinLock<T> {
    raw_lock: RawSpinLock,
    data: UnsafeCell<T>,
}
Expand description

提供对数据的互斥访问的自旋锁结构体。 内部包含一个 RawSpinLock 和一个 UnsafeCell 用于存储数据。 使用示例:

let lock = SpinLock::new(0);
{
    let mut guard = lock.lock(); // 获取锁
    *guard += 1; // 访问和修改数据
} // 离开作用域,自动释放锁

注意:SpinLock 不是可重入的。 当持有锁时,尝试再次获取锁将导致死锁。 确保在同一线程中不会嵌套调用 SpinLock::lock()。 此外,SpinLock 通过禁用中断来保护临界区,因此在持有锁时应避免长时间运行的操作,以防止影响系统响应性。

Fields§

§raw_lock: RawSpinLock§data: UnsafeCell<T>

Implementations§

Source§

impl<T> SpinLock<T>

Source

pub const fn new(data: T) -> Self

创建一个新的 SpinLock 实例,初始化内部数据。

Source

pub fn lock(&self) -> SpinLockGuard<'_, T>

获取自旋锁,并返回一个 RAII 保护器,用于访问和修改内部数据。

Source

pub fn try_lock(&self) -> Option<SpinLockGuard<'_, T>>

尝试获取自旋锁,如果成功则返回 RAII 保护器,否则返回 None。

Trait Implementations§

Source§

impl<T: Debug> Debug for SpinLock<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Send> Send for SpinLock<T>

Source§

impl<T: Send> Sync for SpinLock<T>

Auto Trait Implementations§

§

impl<T> !Freeze for SpinLock<T>

§

impl<T> !RefUnwindSafe for SpinLock<T>

§

impl<T> Unpin for SpinLock<T>
where T: Unpin,

§

impl<T> UnwindSafe for SpinLock<T>
where T: UnwindSafe,

Blanket Implementations§

§

impl<T> Any for T
where T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for T
where T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for T
where T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, U> Into<U> for T
where U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.