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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#![allow(dead_code)]
use super::Task;
use core::fmt;
use core::cell::UnsafeCell;
use core::sync::atomic::AtomicUsize;
use core::sync::atomic::Ordering::{Acquire, Release};
pub struct AtomicTask {
state: AtomicUsize,
task: UnsafeCell<Option<Task>>,
}
const WAITING: usize = 2;
const LOCKED_WRITE: usize = 0;
const LOCKED_WRITE_NOTIFIED: usize = 1;
#[allow(dead_code)]
const LOCKED_READ: usize = 3;
impl AtomicTask {
pub fn new() -> AtomicTask {
fn is_sync<T: Sync>() {}
is_sync::<Task>();
AtomicTask {
state: AtomicUsize::new(WAITING),
task: UnsafeCell::new(None),
}
}
pub unsafe fn park(&self) {
if let Some(ref task) = *self.task.get() {
if task.will_notify_current() {
return
}
}
let task = super::current();
match self.state.compare_and_swap(WAITING, LOCKED_WRITE, Acquire) {
WAITING => {
*self.task.get() = Some(task);
if LOCKED_WRITE_NOTIFIED == self.state.swap(WAITING, Release) {
(*self.task.get()).as_ref().unwrap().notify();
}
}
state => {
debug_assert!(state != LOCKED_WRITE, "unexpected state LOCKED_WRITE");
debug_assert!(state != LOCKED_WRITE_NOTIFIED, "unexpected state LOCKED_WRITE_NOTIFIED");
task.notify();
}
}
}
pub fn notify(&self) {
let mut curr = WAITING;
loop {
if curr == LOCKED_WRITE {
let actual = self.state.compare_and_swap(LOCKED_WRITE, LOCKED_WRITE_NOTIFIED, Release);
if curr == actual {
return;
}
curr = actual;
} else if curr == LOCKED_WRITE_NOTIFIED {
return;
} else {
let actual = self.state.compare_and_swap(curr, curr + 1, Acquire);
if actual == curr {
unsafe {
if let Some(ref task) = *self.task.get() {
task.notify();
}
}
self.state.fetch_sub(1, Release);
return;
}
curr = actual;
}
}
}
}
impl fmt::Debug for AtomicTask {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "AtomicTask")
}
}
unsafe impl Send for AtomicTask {}
unsafe impl Sync for AtomicTask {}