Struct rp2040_hal::sio::Spinlock
source · pub struct Spinlock<const N: usize>(/* private fields */)
where
Spinlock<N>: SpinlockValid;
Expand description
Hardware based spinlock.
You can claim this lock by calling either claim
, try_claim
or
claim_async
. These spin-locks are hardware backed, so if you lock
e.g. Spinlock<6>
, then any other part of your application using
Spinlock<6>
will contend for the same lock, without them needing to
share a reference or otherwise communicate with each other.
When the obtained spinlock goes out of scope, it is automatically unlocked.
use rp2040_hal::sio::Spinlock0;
static mut SOME_GLOBAL_VAR: u32 = 0;
/// This function is safe to call from two different cores, but is not safe
/// to call from an interrupt routine!
fn update_global_var() {
// Do not say `let _ = ` here - it will immediately unlock!
let _lock = Spinlock0::claim();
// Do your thing here that Core 0 and Core 1 might want to do at the
// same time, like update this global variable:
unsafe { SOME_GLOBAL_VAR += 1 };
// The lock is dropped here.
}
Warning: These spinlocks are not re-entrant, meaning that the following code will cause a deadlock:
use rp2040_hal::sio::Spinlock0;
let lock_1 = Spinlock0::claim();
let lock_2 = Spinlock0::claim(); // deadlock here
Note: The critical-section
implementation uses Spinlock 31.
Implementations§
source§impl<const N: usize> Spinlock<N>where
Spinlock<N>: SpinlockValid,
impl<const N: usize> Spinlock<N>where
Spinlock<N>: SpinlockValid,
sourcepub fn try_claim() -> Option<Self>
pub fn try_claim() -> Option<Self>
Try to claim the spinlock. Will return Some(Self)
if the lock is obtained, and None
if the lock is
already in use somewhere else.
sourcepub fn claim() -> Self
pub fn claim() -> Self
Claim the spinlock, will block the current thread until the lock is available.
Note that calling this multiple times in a row will cause a deadlock
sourcepub fn claim_async() -> Result<Self, Infallible>
pub fn claim_async() -> Result<Self, Infallible>
Try to claim the spinlock. Will return WouldBlock
until the spinlock is available.