spin::rwlock

Struct RwLock

source
pub struct RwLock<T: ?Sized, R = Spin> { /* private fields */ }
Expand description

A lock that provides data access to either one writer or many readers.

This lock behaves in a similar manner to its namesake std::sync::RwLock but uses spinning for synchronisation instead. Unlike its namespace, this lock does not track lock poisoning.

This type of lock allows a number of readers or at most one writer at any point in time. The write portion of this lock typically allows modification of the underlying data (exclusive access) and the read portion of this lock typically allows for read-only access (shared access).

The type parameter T represents the data that this lock protects. It is required that T satisfies Send to be shared across tasks and Sync to allow concurrent access through readers. The RAII guards returned from the locking methods implement Deref (and DerefMut for the write methods) to allow access to the contained of the lock.

An RwLockUpgradableGuard can be upgraded to a writable guard through the RwLockUpgradableGuard::upgrade RwLockUpgradableGuard::try_upgrade functions. Writable or upgradeable guards can be downgraded through their respective downgrade functions.

Based on Facebook’s folly/RWSpinLock.h. This implementation is unfair to writers - if the lock always has readers, then no writers will ever get a chance. Using an upgradeable lock guard can somewhat alleviate this issue as no new readers are allowed when an upgradeable guard is held, but upgradeable guards can be taken when there are existing readers. However if the lock is that highly contended and writes are crucial then this implementation may be a poor choice.

§Examples

use spin;

let lock = spin::RwLock::new(5);

// many reader locks can be held at once
{
    let r1 = lock.read();
    let r2 = lock.read();
    assert_eq!(*r1, 5);
    assert_eq!(*r2, 5);
} // read locks are dropped at this point

// only one write lock may be held, however
{
    let mut w = lock.write();
    *w += 1;
    assert_eq!(*w, 6);
} // write lock is dropped here

Implementations§

source§

impl<T, R> RwLock<T, R>

source

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

Creates a new spinlock wrapping the supplied data.

May be used statically:

use spin;

static RW_LOCK: spin::RwLock<()> = spin::RwLock::new(());

fn demo() {
    let lock = RW_LOCK.read();
    // do something with lock
    drop(lock);
}
source

pub fn into_inner(self) -> T

Consumes this RwLock, returning the underlying data.

source

pub fn as_mut_ptr(&self) -> *mut T

Returns a mutable pointer to the underying data.

This is mostly meant to be used for applications which require manual unlocking, but where storing both the lock and the pointer to the inner data gets inefficient.

While this is safe, writing to the data is undefined behavior unless the current thread has acquired a write lock, and reading requires either a read or write lock.

§Example
let lock = spin::RwLock::new(42);

unsafe {
    core::mem::forget(lock.write());

    assert_eq!(lock.as_mut_ptr().read(), 42);
    lock.as_mut_ptr().write(58);

    lock.force_write_unlock();
}

assert_eq!(*lock.read(), 58);
source§

impl<T: ?Sized, R: RelaxStrategy> RwLock<T, R>

source

pub fn read(&self) -> RwLockReadGuard<'_, T>

Locks this rwlock with shared read access, blocking the current thread until it can be acquired.

The calling thread will be blocked until there are no more writers which hold the lock. There may be other readers currently inside the lock when this method returns. This method does not provide any guarantees with respect to the ordering of whether contentious readers or writers will acquire the lock first.

Returns an RAII guard which will release this thread’s shared access once it is dropped.

let mylock = spin::RwLock::new(0);
{
    let mut data = mylock.read();
    // The lock is now locked and the data can be read
    println!("{}", *data);
    // The lock is dropped
}
source

pub fn write(&self) -> RwLockWriteGuard<'_, T, R>

Lock this rwlock with exclusive write access, blocking the current thread until it can be acquired.

This function will not return while other writers or other readers currently have access to the lock.

Returns an RAII guard which will drop the write access of this rwlock when dropped.

let mylock = spin::RwLock::new(0);
{
    let mut data = mylock.write();
    // The lock is now locked and the data can be written
    *data += 1;
    // The lock is dropped
}
source

pub fn upgradeable_read(&self) -> RwLockUpgradableGuard<'_, T, R>

Obtain a readable lock guard that can later be upgraded to a writable lock guard. Upgrades can be done through the RwLockUpgradableGuard::upgrade method.

source§

impl<T: ?Sized, R> RwLock<T, R>

source

pub fn try_read(&self) -> Option<RwLockReadGuard<'_, T>>

Attempt to acquire this lock with shared read access.

This function will never block and will return immediately if read would otherwise succeed. Returns Some of an RAII guard which will release the shared access of this thread when dropped, or None if the access could not be granted. This method does not provide any guarantees with respect to the ordering of whether contentious readers or writers will acquire the lock first.

let mylock = spin::RwLock::new(0);
{
    match mylock.try_read() {
        Some(data) => {
            // The lock is now locked and the data can be read
            println!("{}", *data);
            // The lock is dropped
        },
        None => (), // no cigar
    };
}
source

pub fn reader_count(&self) -> usize

Return the number of readers that currently hold the lock (including upgradable readers).

§Safety

This function provides no synchronization guarantees and so its result should be considered ‘out of date’ the instant it is called. Do not use it for synchronization purposes. However, it may be useful as a heuristic.

source

pub fn writer_count(&self) -> usize

Return the number of writers that currently hold the lock.

Because RwLock guarantees exclusive mutable access, this function may only return either 0 or 1.

§Safety

This function provides no synchronization guarantees and so its result should be considered ‘out of date’ the instant it is called. Do not use it for synchronization purposes. However, it may be useful as a heuristic.

source

pub unsafe fn force_read_decrement(&self)

Force decrement the reader count.

§Safety

This is extremely unsafe if there are outstanding RwLockReadGuards live, or if called more times than read has been called, but can be useful in FFI contexts where the caller doesn’t know how to deal with RAII. The underlying atomic operation uses Ordering::Release.

source

pub unsafe fn force_write_unlock(&self)

Force unlock exclusive write access.

§Safety

This is extremely unsafe if there are outstanding RwLockWriteGuards live, or if called when there are current readers, but can be useful in FFI contexts where the caller doesn’t know how to deal with RAII. The underlying atomic operation uses Ordering::Release.

source

pub fn try_write(&self) -> Option<RwLockWriteGuard<'_, T, R>>

Attempt to lock this rwlock with exclusive write access.

This function does not ever block, and it will return None if a call to write would otherwise block. If successful, an RAII guard is returned.

let mylock = spin::RwLock::new(0);
{
    match mylock.try_write() {
        Some(mut data) => {
            // The lock is now locked and the data can be written
            *data += 1;
            // The lock is implicitly dropped
        },
        None => (), // no cigar
    };
}
source

pub fn try_upgradeable_read(&self) -> Option<RwLockUpgradableGuard<'_, T, R>>

Tries to obtain an upgradeable lock guard.

source

pub fn get_mut(&mut self) -> &mut T

Returns a mutable reference to the underlying data.

Since this call borrows the RwLock mutably, no actual locking needs to take place – the mutable borrow statically guarantees no locks exist.

§Examples
let mut lock = spin::RwLock::new(0);
*lock.get_mut() = 10;
assert_eq!(*lock.read(), 10);

Trait Implementations§

source§

impl<T: ?Sized + Debug, R> Debug for RwLock<T, R>

source§

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

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

impl<T: ?Sized + Default, R> Default for RwLock<T, R>

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<T, R> From<T> for RwLock<T, R>

source§

fn from(data: T) -> Self

Converts to this type from the input type.
source§

impl<R: RelaxStrategy> RawRwLock for RwLock<(), R>

source§

const INIT: Self = _

Initial value for an unlocked RwLock.
source§

type GuardMarker = GuardSend

Marker type which determines whether a lock guard should be Send. Use one of the GuardSend or GuardNoSend helper types here.
source§

fn lock_exclusive(&self)

Acquires an exclusive lock, blocking the current thread until it is able to do so.
source§

fn try_lock_exclusive(&self) -> bool

Attempts to acquire an exclusive lock without blocking.
source§

unsafe fn unlock_exclusive(&self)

Releases an exclusive lock. Read more
source§

fn lock_shared(&self)

Acquires a shared lock, blocking the current thread until it is able to do so.
source§

fn try_lock_shared(&self) -> bool

Attempts to acquire a shared lock without blocking.
source§

unsafe fn unlock_shared(&self)

Releases a shared lock. Read more
source§

fn is_locked(&self) -> bool

Checks if this RwLock is currently locked in any way.
source§

fn is_locked_exclusive(&self) -> bool

Check if this RwLock is currently exclusively locked.
source§

impl<R: RelaxStrategy> RawRwLockDowngrade for RwLock<(), R>

source§

unsafe fn downgrade(&self)

Atomically downgrades an exclusive lock into a shared lock without allowing any thread to take an exclusive lock in the meantime. Read more
source§

impl<R: RelaxStrategy> RawRwLockUpgrade for RwLock<(), R>

source§

fn lock_upgradable(&self)

Acquires an upgradable lock, blocking the current thread until it is able to do so.
source§

fn try_lock_upgradable(&self) -> bool

Attempts to acquire an upgradable lock without blocking.
source§

unsafe fn unlock_upgradable(&self)

Releases an upgradable lock. Read more
source§

unsafe fn upgrade(&self)

Upgrades an upgradable lock to an exclusive lock. Read more
source§

unsafe fn try_upgrade(&self) -> bool

Attempts to upgrade an upgradable lock to an exclusive lock without blocking. Read more
source§

impl<T: ?Sized + Send, R> Send for RwLock<T, R>

source§

impl<T: ?Sized + Send + Sync, R> Sync for RwLock<T, R>

Auto Trait Implementations§

§

impl<T, R = Spin> !Freeze for RwLock<T, R>

§

impl<T, R = Spin> !RefUnwindSafe for RwLock<T, R>

§

impl<T, R> Unpin for RwLock<T, R>
where R: Unpin, T: Unpin + ?Sized,

§

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

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<!> for T

source§

fn from(t: !) -> T

Converts to this type from the input type.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

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

source§

fn into(self) -> U

Calls U::from(self).

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

source§

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

source§

type Error = Infallible

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

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

Performs the conversion.
source§

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

source§

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

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

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

Performs the conversion.