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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#![cfg_attr(all(test, feature = "bench"), feature(test))]
#[cfg(all(test, feature = "bench"))]
extern crate test;
#[cfg(test)]
mod tests;
#[cfg(target_os = "linux")]
pub use linux::Once;
#[cfg(not(target_os = "linux"))]
pub use std::sync::Once;
#[cfg(target_os = "linux")]
mod linux {
use linux_futex::{Futex, Private};
use core::sync::atomic::Ordering;
pub struct Once(Futex<Private>);
const INCOMPLETE: i32 = 0;
const POISONED: i32 = 2;
const COMPLETE: i32 = 1;
const RUNNING_NO_WAIT: i32 = 3;
const RUNNING_WAITING: i32 = 4;
impl Once {
pub const fn new() -> Self {
Once(Futex::new(INCOMPLETE))
}
pub fn call_once<F: FnOnce()>(&self, f: F) {
let state = self.0.value.load(Ordering::Acquire);
if state == COMPLETE {
return;
}
let mut f = Some(f);
self.internal_call_once(state, &mut || f.take().expect("closure called more than once")())
}
#[cold]
fn internal_call_once(&self, mut state: i32, f: &mut dyn FnMut()) {
struct PanicChecker<'a> {
futex: &'a Futex<Private>,
value_to_write: i32,
}
impl<'a> Drop for PanicChecker<'a> {
fn drop(&mut self) {
if self.futex.value.swap(self.value_to_write, Ordering::AcqRel) == RUNNING_WAITING {
self.futex.wake(i32::max_value());
}
}
}
loop {
match state {
INCOMPLETE => {
if let Err(old) = self.0.value.compare_exchange_weak(INCOMPLETE, RUNNING_NO_WAIT, Ordering::Acquire, Ordering::Acquire) {
state = old;
continue;
}
{
let mut panic_checker = PanicChecker { futex: &self.0, value_to_write: POISONED, };
f();
panic_checker.value_to_write = COMPLETE;
}
break;
},
COMPLETE => break,
POISONED => panic!("Once instance has previously been poisoned"),
_running => {
if let Err(old) = self.0.value.compare_exchange(RUNNING_NO_WAIT, RUNNING_WAITING, Ordering::AcqRel, Ordering::Acquire) {
state = old;
} else {
state = RUNNING_WAITING;
}
while state >= RUNNING_NO_WAIT {
let _ = self.0.wait(state);
state = self.0.value.load(Ordering::Acquire);
}
break;
},
}
}
}
pub fn is_completed(&self) -> bool {
self.0.value.load(Ordering::Acquire) == COMPLETE
}
}
}
#[cfg(test)]
mod our_tests {
use super::Once;
use std::sync::{Arc, atomic::{AtomicUsize, Ordering::Relaxed}};
#[cfg(feature = "bench")]
use test::Bencher;
#[cfg(feature = "bench")]
const CONTENDED_THREADS: usize = 5;
#[cfg(feature = "bench")]
const CONTENDED_WAIT: u64 = 1_000_000;
#[test]
fn basic() {
let mut ran = false;
let once = Once::new();
once.call_once(|| ran = true);
assert!(ran);
ran = false;
once.call_once(|| ran = true);
assert!(!ran);
}
#[test]
fn multithreaded() {
let once = Arc::new((Once::new(), AtomicUsize::new(0)));
let once_cloned = Arc::clone(&once);
let handle = std::thread::spawn(move || once_cloned.0.call_once(|| { once_cloned.1.fetch_add(1, Relaxed); }));
once.0.call_once(|| { once.1.fetch_add(1, Relaxed); });
handle.join().expect("failed to join thread");
assert_eq!(once.1.load(Relaxed), 1);
}
#[bench]
#[cfg(feature = "bench")]
#[cfg_attr(miri, ignore)]
fn measure_std_trivial(bencher: &mut Bencher) {
bencher.iter(|| {
let mut ran = false;
let once = std::sync::Once::new();
once.call_once(|| ran = true);
assert!(ran);
})
}
#[bench]
#[cfg(feature = "bench")]
#[cfg_attr(miri, ignore)]
fn measure_linux_trivial(bencher: &mut Bencher) {
bencher.iter(|| {
let mut ran = false;
let once = Once::new();
once.call_once(|| ran = true);
assert!(ran);
})
}
#[bench]
#[cfg(feature = "bench")]
#[cfg_attr(miri, ignore)]
fn measure_std_contended(bencher: &mut Bencher) {
let barrier = Arc::new(std::sync::Barrier::new(CONTENDED_THREADS));
bencher.iter(|| {
let once = Arc::new(std::sync::Once::new());
let threads = (0..CONTENDED_THREADS)
.into_iter()
.map(|_| {
let cloned_once = Arc::clone(&once);
let cloned_barrier = Arc::clone(&barrier);
std::thread::spawn(move || {
cloned_barrier.wait();
cloned_once.call_once(|| std::thread::sleep(std::time::Duration::from_nanos(CONTENDED_WAIT)))
})
})
.collect::<Vec<_>>();
threads
.into_iter()
.map(|thread| thread.join().map(drop))
.collect::<Result<(), _>>()
.expect("Failed to join");
})
}
#[bench]
#[cfg(feature = "bench")]
#[cfg_attr(miri, ignore)]
fn measure_linux_contended(bencher: &mut Bencher) {
let barrier = Arc::new(std::sync::Barrier::new(CONTENDED_THREADS));
bencher.iter(|| {
let once = Arc::new(Once::new());
let threads = (0..CONTENDED_THREADS)
.into_iter()
.map(|_| {
let cloned = Arc::clone(&once);
let cloned_barrier = Arc::clone(&barrier);
std::thread::spawn(move || {
cloned_barrier.wait();
cloned.call_once(|| std::thread::sleep(std::time::Duration::from_nanos(CONTENDED_WAIT)))
})
})
.collect::<Vec<_>>();
threads
.into_iter()
.map(|thread| thread.join().map(drop))
.collect::<Result<(), _>>()
.expect("Failed to join");
})
}
}