diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 620780c4..22c25af6 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -273,7 +273,7 @@ - [aarch64-paging](bare-metal/useful-crates/aarch64-paging.md) - [buddy_system_allocator](bare-metal/useful-crates/buddy_system_allocator.md) - [tinyvec](bare-metal/useful-crates/tinyvec.md) - - [spin and once_cell]() + - [spin](bare-metal/useful-crates/spin.md) - [Android]() - [vmbase]() - [Exercises](exercises/bare-metal/afternoon.md) diff --git a/src/bare-metal/useful-crates/spin.md b/src/bare-metal/useful-crates/spin.md new file mode 100644 index 00000000..3d2a9976 --- /dev/null +++ b/src/bare-metal/useful-crates/spin.md @@ -0,0 +1,32 @@ +# `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`][1] crate provides spinlock-based equivalents of many of these primitives. + +```rust,editable,compile_fail +use spin::mutex::SpinMutex; + +static counter: SpinMutex = SpinMutex::new(0); + +fn main() { + println!("count: {}", counter.lock()); + *counter.lock() += 2; + println!("count: {}", counter.lock()); +} +``` + +
+ +* 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`][2] crate also has some useful types for late initialisation with a slightly + different approach to `spin::once::Once`. + +
+ +[1]: https://crates.io/crates/spin +[2]: https://crates.io/crates/once_cell