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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
use fnv::FnvHasher;
use std::cmp::Ordering;
use std::hash::{Hash,Hasher};
use std::sync::Arc;
use std::sync::atomic::{self, AtomicBool};
use std::thread::{self, Thread};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct Prio {
prio: usize,
thread_hash: u64,
}
impl Prio {
pub fn new(prio: usize) -> Prio {
let mut s = FnvHasher::default();
thread::current().id().hash(&mut s);
Prio {
prio: prio,
thread_hash: s.finish(),
}
}
}
#[derive(Debug, Clone)]
pub struct PV<P,V> {
pub p: P,
pub v: V,
}
impl<P:PartialEq,V> PartialEq for PV<P,V> {
fn eq(&self, other: &PV<P,V>) -> bool { other.p == self.p }
}
impl<P:Eq,V> Eq for PV<P,V> {}
impl<P:PartialOrd,V> PartialOrd for PV<P,V> {
fn partial_cmp(&self, other: &PV<P,V>) -> Option<Ordering> { other.p.partial_cmp(&self.p) }
}
impl<P:Ord,V> Ord for PV<P,V> {
fn cmp(&self, other: &PV<P,V>) -> Ordering { other.p.cmp(&self.p) }
}
pub fn create_tokens() -> (SleepToken, WakeToken) {
let token = Arc::new(Token {
thread: thread::current(),
is_woken: AtomicBool::new(false),
});
(SleepToken(token.clone()), WakeToken(token))
}
#[derive(Debug)]
struct Token {
thread: Thread,
is_woken: AtomicBool,
}
#[derive(Debug)]
pub struct SleepToken(Arc<Token>);
#[derive(Debug)]
pub struct WakeToken(Arc<Token>);
impl SleepToken {
pub fn sleep(self) {
while !self.0.is_woken.load(atomic::Ordering::SeqCst) {
thread::park();
}
}
}
impl WakeToken {
pub fn wake(self) {
let already_woken = self.0.is_woken.compare_and_swap(false, true, atomic::Ordering::SeqCst);
assert!(!already_woken, "this token was signalled twice!");
self.0.thread.unpark();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tokens() {
let (sleep_token, wake_token) = create_tokens();
wake_token.wake();
sleep_token.sleep();
println!("woke!");
}
}