SpinLock

Struct SpinLock 

Source
pub struct SpinLock<T: ?Sized> {
    locked: AtomicBool,
    _pad: [u8; 15],
    data: UnsafeCell<T>,
}
Expand description

A mutual exclusion primitive useful for protecting shared data

This spinlock will block threads waiting for the lock to become available. The spinlock can be created via a new constructor. Each spinlock has a type parameter which represents the data that it is protecting. The data can only be accessed through the guards returned from lock and try_lock, which guarantees that the data is only ever accessed when the spinlock is locked.

§Examples

use alloc::sync::Arc;
use keos::sync::SpinLock;
use keos::thread;

const N: usize = 10;

// Spawn a few threads to increment a shared variable (non-atomically), and
// let the main thread know once all increments are done.
//
// Here we're using an Arc to share memory among threads, and the data inside
// the Arc is protected with a spinlock.
let data = Arc::new(SpinLock::new(0));

for _ in 0..N {
    let data = Arc::clone(&data);
    thread::ThreadBuilder::new("work").spawn(move || {
        // The shared state can only be accessed once the lock is held.
        // Our non-atomic increment is safe because we're the only thread
        // which can access the shared state when the lock is held.
        //
        // We unwrap() the return value to assert that we are not expecting
        // threads to ever fail while holding the lock.
        let mut guard = data.lock();
        guard += 1;
        // the lock must be "explicitly" unlocked before `guard` goes out of scope.
        guard.unlock();
    });
}

Fields§

§locked: AtomicBool§_pad: [u8; 15]§data: UnsafeCell<T>

Implementations§

Source§

impl<T> SpinLock<T>

Source

pub const fn new(t: T) -> SpinLock<T>

Creates a new spinlock in an unlocked state ready for use.

§Examples
use keos::sync::SpinLock;

let spinlock = SpinLock::new(0);
Source§

impl<T: ?Sized> SpinLock<T>

Source

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

Acquires a spinlock, blocking the current thread until it is able to do so.

This function will block the local thread until it is available to acquire the spinlock. Upon returning, the thread is the only thread with the lock held. An guard is returned to allow scoped access of the lock. When the guard goes out of scope without [SpinLockGuard::unlock], panic occurs.

The exact behavior on locking a spinlock in the thread which already holds the lock is left unspecified. However, this function will not return on the second call (it might panic or deadlock, for example).

§Examples
use alloc::sync::Arc;
use keos::sync::SpinLock;
use keos::thread;

let spinlock = Arc::new(SpinLock::new(0));
let c_spinlock = Arc::clone(&spinlock);

thread::spawn(move || {
    let mut guard = c_spinlock.lock();
    *guard = 10;
    guard.unlock();
}).join().expect("thread::spawn failed");
let guard = spinlock.lock();
assert_eq!(*guard, 10);
guard.unlock();
Source

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

Attempts to acquire this lock.

If the lock could not be acquired at this time, then [Err] is returned. Otherwise, an guard is returned. The lock will be unlocked when the guard is dropped.

This function does not block.

§Errors

If the spinlock could not be acquired because it is already locked, then this call will return the [WouldBlock] error.

§Examples
use keos::sync::SpinLock;
use alloc::sync::Arc;
use keos::thread;

let spinlock = Arc::new(SpinLock::new(0));
let c_spinlock = Arc::clone(&spinlock);

thread::spawn(move || {
    let mut lock = c_spinlock.try_lock();
    if let Ok(ref mut spinlock) = lock {
        **spinlock = 10;
    } else {
        println!("try_lock failed");
    }
}).join().expect("thread::spawn failed");
let guard = spinlock.lock();
assert_eq!(*guard, 10);
guard.unlock();
Source

pub fn into_inner(self) -> T
where T: Sized,

Consumes this spinlock, returning the underlying data.

§Examples
use keos::sync::SpinLock;

let spinlock = SpinLock::new(0);
assert_eq!(spinlock.into_inner().unwrap(), 0);

Trait Implementations§

Source§

impl<T: Default> Default for SpinLock<T>

Source§

fn default() -> SpinLock<T>

Creates a SpinLock<T>, with the Default value for T.

Source§

impl<T: ?Sized + Send> Send for SpinLock<T>

Source§

impl<T: ?Sized + 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 + ?Sized,

§

impl<T> UnwindSafe for SpinLock<T>
where T: UnwindSafe + ?Sized,

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.