spin

std::sync::Mutex and the other synchronisation primitives from std::sync are not available in core or alloc. How can we manage synchronisation or interior mutability, such as for sharing state between different CPUs?

The spin crate provides spinlock-based equivalents of many of these primitives.

  1. use spin::mutex::SpinMutex;
  2. static counter: SpinMutex<u32> = SpinMutex::new(0);
  3. fn main() {
  4.     println!("count: {}", counter.lock());
  5.     *counter.lock() += 2;
  6.     println!("count: {}", counter.lock());
  7. }
  • Be careful to avoid deadlock if you take locks in interrupt handlers.
  • spin also has a ticket lock mutex implementation; equivalents of RwLock, Barrier and Once from std::sync; and Lazy for lazy initialisation.
  • The once_cell crate also has some useful types for late initialisation with a slightly different approach to spin::once::Once.
  • The Rust Playground includes spin, so this example will run fine inline.