-
Notifications
You must be signed in to change notification settings - Fork 109
/
ch3-08-lock.rs
25 lines (22 loc) · 729 Bytes
/
ch3-08-lock.rs
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
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::{Acquire, Relaxed, Release};
use std::thread;
static mut DATA: String = String::new();
static LOCKED: AtomicBool = AtomicBool::new(false);
fn f() {
if LOCKED.compare_exchange(false, true, Acquire, Relaxed).is_ok() {
// Safety: We hold the exclusive lock, so nothing else is accessing DATA.
unsafe { DATA.push('!') };
LOCKED.store(false, Release);
}
}
fn main() {
thread::scope(|s| {
for _ in 0..100 {
s.spawn(f);
}
});
// DATA now contains at least one exclamation mark (and maybe more).
assert!(unsafe { DATA.len() } > 0);
assert!(unsafe { DATA.chars().all(|c| c == '!') });
}