rust / expert
Snippet
Erstellung eines leichtgewichtigen Mutex mittels atomarer CAS-Operationen
Zeigt Low-Level-Synchronisation mittels atomarer Primitive. Es implementiert einen einfachen Spinlock-Mutex und einen RAII-Guard für Thread-Sicherheit ohne Overheads des Betriebssystems.
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);}}
Erklärung
1
locked: AtomicBool,
Hält den Sperrzustand mithilfe eines atomaren Booleans, das Thread-sichere Änderungen garantiert.
2
while self.locked.compare_exchange_weak(
Versucht ein atomares Compare-And-Swap (CAS) und setzt das Flag auf true, wenn es false war.
3
std::hint::spin_loop();
Signalisiert dem Prozessor, dass der Thread im Busy-Waiting-Zustand ist, was Strom und Pipeline-Ressourcen schont.
4
self.lock.locked.store(false, Ordering::Release);
Stellt sicher, dass vorherige Schreiboperationen für andere Threads sichtbar sind, bevor der Sperrzustand freigegeben wird.