|
|
@ -210,18 +210,18 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
|
|
|
use std::thread;
|
|
|
|
use std::thread;
|
|
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
fn main() {
|
|
|
|
let lock = Arc::new(AtomicBool::new(true)); // value answers "am I locked?"
|
|
|
|
let lock = Arc::new(AtomicBool::new(false)); // value answers "am I locked?"
|
|
|
|
|
|
|
|
|
|
|
|
// ... distribute lock to threads somehow ...
|
|
|
|
// ... distribute lock to threads somehow ...
|
|
|
|
|
|
|
|
|
|
|
|
// Try to acquire the lock by setting it to false
|
|
|
|
// Try to acquire the lock by setting it to true
|
|
|
|
while !lock.compare_and_swap(true, false, Ordering::Acquire) { }
|
|
|
|
while lock.compare_and_swap(false, true, Ordering::Acquire) { }
|
|
|
|
// broke out of the loop, so we successfully acquired the lock!
|
|
|
|
// broke out of the loop, so we successfully acquired the lock!
|
|
|
|
|
|
|
|
|
|
|
|
// ... scary data accesses ...
|
|
|
|
// ... scary data accesses ...
|
|
|
|
|
|
|
|
|
|
|
|
// ok we're done, release the lock
|
|
|
|
// ok we're done, release the lock
|
|
|
|
lock.store(true, Ordering::Release);
|
|
|
|
lock.store(false, Ordering::Release);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|