forked from compio-rs/synchrony
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflag.rs
More file actions
60 lines (49 loc) · 1.58 KB
/
flag.rs
File metadata and controls
60 lines (49 loc) · 1.58 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
//! Boolean flags
/// Multithreaded boolean flag based on [`std::sync::atomic::AtomicBool`]
pub mod sync {
super::impl_flag!(sync);
impl crate::AssertMt for Flag {}
}
/// Singlethreaded boolean flag based on [`std::cell::Cell`]
pub mod unsync {
super::impl_flag!(unsync);
}
macro_rules! impl_flag {
($sync:ident) => {
use std::sync::atomic::Ordering;
use crate::$sync::atomic::AtomicBool;
/// A boolean flag
pub struct Flag(AtomicBool);
impl Flag {
/// Create a new flag
pub fn new(val: bool) -> Self {
Flag(AtomicBool::new(val))
}
/// Get the current value
pub fn get(&self) -> bool {
self.0.load(Ordering::Acquire)
}
/// Stores a value into the bool, returning the previous value.
pub fn swap(&self, val: bool) -> bool {
self.0.swap(val, Ordering::AcqRel)
}
/// Flip the current value and return the new value
pub fn flip(&self) -> bool {
let mut current = self.get();
loop {
let new = !current;
match self.0.compare_exchange_weak(
current,
new,
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => return new,
Err(previous) => current = previous,
}
}
}
}
};
}
use impl_flag;