rust / expert
Snippet
Building a Lightweight Mutex Using Atomic CAS Operations
Demonstrates low-level concurrency synchronization using atomic primitives. It implements a basic spinlock mutex and RAII guard for thread safety without operating system mutex overhead.
snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use std::sync::atomic::{AtomicBool, Ordering};use std::cell::UnsafeCell;pub struct Spinlock<T> {locked: AtomicBool,data: UnsafeCell<T>,}unsafe impl<T: Send> Sync for Spinlock<T> {}impl<T> Spinlock<T> {pub const fn new(value: T) -> Self {Self {locked: AtomicBool::new(false),data: UnsafeCell::new(value),}}pub fn lock(&self) -> SpinlockGuard<'_, T> {while self.locked.compare_exchange_weak(false,true,Ordering::Acquire,Ordering::Relaxed).is_err() {std::hint::spin_loop();}SpinlockGuard { lock: self }}}pub struct SpinlockGuard<'a, T> {lock: &'a Spinlock<T>,}impl<T> std::ops::Deref for SpinlockGuard<'_, T> {type Target = T;fn deref(&self) -> &Self::Target {unsafe { &*self.lock.data.get() }}}impl<T> Drop for SpinlockGuard<'_, T> {fn drop(&mut self) {self.lock.locked.store(false, Ordering::Release);}}
Breakdown
1
locked: AtomicBool,
Holds the lock state using an atomic boolean that guarantees thread-safe modifications.
2
while self.locked.compare_exchange_weak(
Attempts atomic Compare-And-Swap (CAS), updating flag to true if it was false.
3
std::hint::spin_loop();
Signals the processor that the thread is busy-waiting, reducing power and pipeline consumption.
4
self.lock.locked.store(false, Ordering::Release);
Ensures prior write operations are visible to other threads before releasing the lock state.