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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use core::cell::UnsafeCell;
use core::fmt::{Debug, Formatter};
use core::mem::{forget, ManuallyDrop};
use core::ops::DerefMut;
use core::sync::atomic::*;
use core::convert::identity;
/// Wrapper struct that allows modifying and swapping value without using locks.
///
/// AtomicCell does not use atomic load/store/cas on contained data so that it can hold structs
/// of arbitrary size.
pub struct AtomicCell<T> {
mark: AtomicBool,
cell: UnsafeCell<ManuallyDrop<T>>,
}
unsafe impl<T> Send for AtomicCell<T> where T: Send + Sync {}
unsafe impl<T> Sync for AtomicCell<T> where T: Send + Sync {}
impl<T> AtomicCell<T> {
/// Create new atomic cell with initial value.
pub const fn new(value: T) -> Self {
Self {
mark: AtomicBool::new(false),
cell: UnsafeCell::new(ManuallyDrop::new(value)),
}
}
/// Tries to swap the value inside cell.
///
/// When successful returns `Ok` with previous value. In case of failure, returns `Err` with
/// argument passed to it, returning ownership of value.
///
/// AtomicCell does not use atomic load/store/cas on contained data so that it can hold structs
/// of arbitrary size. This method might fail in case some other thread is now modifying this value.
/// In case of failure you can perform additional checks or try to swap value again until success.
pub fn try_swap(&self, value: T) -> Result<T, T> {
let res = self.mark.compare_exchange_weak(false, true, Ordering::AcqRel, Ordering::Acquire);
if res.unwrap_or_else(identity) {
Err(value) //other thread interfered
} else {
//we know for sure we are only thread writing to this location
//swap values
unsafe {
let first = self.cell.get().read_volatile();
self.cell.get().write_volatile(ManuallyDrop::new(value));
self.mark.store(false, Ordering::Release);
Ok(ManuallyDrop::into_inner(first))
}
}
}
/// Swap the value inside cell.
///
/// Returns previous value from cell.
///
/// AtomicCell does not use atomic load/store/cas on contained data so that it can hold structs
/// of arbitrary size. This method tries to swap value in busy loop until success.
pub fn swap(&self, mut value: T) -> T {
loop {
match self.try_swap(value) {
Ok(val) => return val,
Err(val) => {
value = val;
spin_loop_hint();
}
}
}
}
/// Tries to perform action on value inside cell, possibly mutating it.
///
/// When successful returns `Ok` with value returned from executed function.
/// In case of failure, returns `Err` with argument passed to it,
/// returning ownership of function.
///
/// `T` is required to be copy in case if given function panics. When this occurs, the value is
/// restored to state from before applying the function and panic is propagated.
///
/// AtomicCell does not use atomic load/store/cas on contained data so that it can hold structs
/// of arbitrary size. This method might fail in case some other thread is now modifying this value.
/// In case of failure you can perform additional checks or try to apply action again until success.
pub fn try_apply<F, R>(&self, func: F) -> Result<R, F> where F: FnOnce(&mut T) -> R, T: Copy {
let res = self.mark.compare_exchange_weak(false, true, Ordering::AcqRel, Ordering::Acquire);
if res.unwrap_or_else(identity) {
Err(func) //other thread interfered
} else {
//we know for sure we are only thread writing to this location
struct UnwindGuard<'a>(&'a AtomicBool);
impl<'a> Drop for UnwindGuard<'a> {
fn drop(&mut self) { //perform cleanup on normal execution and if closure panics
self.0.store(false, Ordering::Release);
}
}
//modify value
unsafe {
let mut first = self.cell.get().read_volatile();
let guard = UnwindGuard(&self.mark);
let res = func(&mut first.deref_mut());//modify local copy to ensure volatile operations
self.cell.get().write_volatile(first);
drop(guard);//explicit drop
Ok(res)
}
}
}
/// Perform action on value inside cell, possibly mutating it.
///
/// Returns value returned from executed function.
///
/// `T` is required to be copy in case if given function panics. When this occurs, the value is
/// restored to state from before applying the function and panic is propagated.
///
/// AtomicCell does not use atomic load/store/cas on contained data so that it can hold structs
/// of arbitrary size. This method tries to apply function in busy loop until success.
pub fn apply<F, R>(&self, mut func: F) -> R where F: FnOnce(&mut T) -> R, T: Copy {
loop {
match self.try_apply(func) {
Ok(res) => return res,
Err(f) => {
func = f;
spin_loop_hint();
}
}
}
}
/// Get mutable reference to content of this struct. This method statically ensures that mutation
/// is allowed because it takes self by mutable reference.
#[inline(always)]
pub fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.cell.get() }
}
/// Takes ownership of cell and extracts wrapped value from it.
#[inline(always)]
pub fn into_inner(self) -> T {
unsafe {
let data = self.cell.get().read();
forget(self);//don't run destructor
ManuallyDrop::into_inner(data)
}
}
}
impl<T> Drop for AtomicCell<T> {
fn drop(&mut self) {
unsafe {
ManuallyDrop::drop(&mut *self.cell.get());
}
}
}
impl<T: Debug> Debug for AtomicCell<T> {
//Debug bound just in case we will support showing content.
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "AtomicCell<{}>", core::any::type_name::<T>())?;
f.debug_struct("").field("holds_lock", &self.mark.load(Ordering::Relaxed)).finish()
}
}
#[cfg(test)]
mod test {
extern crate std;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::mem::replace;
use std::num::*;
use std::prelude::v1::*;
use std::sync::{Arc, Barrier};
use std::thread::spawn;
use super::*;
fn test_swap_many_case<T, F>(threads: u64, per_thread: u64, mut factory: impl FnMut(u64) -> T, op: F)
where T: Send + Sync + Eq + Hash + 'static,
F: Fn(&AtomicCell<Option<T>>, Option<T>) -> Option<T> + Send + Sync + 'static {
let swap = Arc::new(AtomicCell::new(None));
let op = Arc::new(op);
let thr = (0..threads).map(|t| {
let mut v = Vec::new();
for i in 0..per_thread {
v.push(Some(factory(t * per_thread + i + 1)));
}
(v, swap.clone(), op.clone())
}).collect::<Vec<_>>().into_iter().map(|(vec, swap, op)| spawn(move || {
let mut res = Vec::new();
for val in vec {
res.push(op(&swap, val));
}
res
})).collect::<Vec<_>>();
let mut data = thr.into_iter().map(|j| j.join().unwrap()).flatten().collect::<HashSet<_>>();
data.insert(op(&swap, None));
assert!(data.contains(&None));
let res = (1..(per_thread * threads + 1)).filter(|v| !data.contains(&Some(factory(*v)))).collect::<Vec<_>>();
assert!(res.is_empty(), "Results not empty {:#?}", &res);
}
fn test_swap_single_case<T, F>(threads: usize, iters: usize, repeats: usize, default: T, unique: T, op: F)
where T: Send + Sync + Eq + Clone + 'static,
F: Fn(&AtomicCell<T>, T) -> T + Send + Sync + 'static {
let barriers = Arc::new((Barrier::new(threads + 1), Barrier::new(threads + 1), Barrier::new(threads + 1)));
let swap = Arc::new(AtomicCell::new(default.clone()));
let op = Arc::new(op);
let handles = (0..threads).map(|_| {
let b = barriers.clone();
let default = default.clone();
let unique = unique.clone();
let swap = swap.clone();
let op = op.clone();
spawn(move || {
let mut it = Vec::with_capacity(iters);
for _ in 0..iters {
let mut v = Vec::with_capacity(repeats + 1);
b.0.wait();
b.1.wait();
for _ in 0..repeats {
v.push(op(&swap, default.clone()));
}
b.2.wait();
v.push(op(&swap, default.clone()));
it.push(v.into_iter().find(|v| v == &unique).is_some());
}
it
})
}).collect::<Vec<_>>();
let mut defs = Vec::with_capacity(iters);
for _ in 0..iters {
barriers.0.wait();
op(&swap, default.clone());
barriers.1.wait();
defs.push(op(&swap, unique.clone()));
barriers.2.wait();
}
let results = handles.into_iter().map(|v| v.join().unwrap()).collect::<Vec<_>>();
assert!(defs.into_iter().all(|v| v == default));
let len = results.iter().map(|v| v.len()).min().unwrap();
assert_eq!(len, iters);
for i in 0..iters {
let count = results.iter().filter(|v| v[i]).count();
assert_eq!(count, 1); //only exactly single swap resulted in other value in each iteration
}
}
#[derive(Clone, Eq, PartialEq, Hash)]
struct TestData {
d0: [u64; 32],
d1: [u64; 32],
d2: [u64; 32],
d3: [u64; 32],
}
//large struct to test statistical data integrity
impl TestData {
pub fn new(val: u64) -> Self {
let (mut d1, mut d2, mut d3) = ([0; 32], [0; 32], [0; 32]);
let mut h = DefaultHasher::default();
for a in d1.iter_mut() {
h.write_u64(val);
*a = h.finish();
}
for a in d2.iter_mut() {
h.write_u64(val);
*a = h.finish();
}
for a in d3.iter_mut() {
h.write_u64(val);
*a = h.finish();
}
Self {
d0: [val; 32],
d1,
d2,
d3,
}
}
}
fn swap_func<T>() -> impl Fn(&AtomicCell<T>, T) -> T { |s, o| s.swap(o) }
fn apply_func<T: Copy>() -> impl Fn(&AtomicCell<T>, T) -> T {
|s, o| {
s.apply(move |val| {
replace(val, o)
})
}
}
#[test]
fn test_basic() {
let swap = AtomicCell::new(1);
assert_eq!(swap.try_swap(2), Ok(1));
assert_eq!(swap.swap(3), 2);
assert_eq!(swap.swap(12345), 3);
swap.try_apply(|val| {
assert_eq!(*val, 12345);
*val = 10;
}).ok().unwrap();
assert_eq!(swap.swap(0), 10);
}
#[test]
fn test_swap_single() {
test_swap_single_case(8, 1000, 1000, 11, 22, swap_func());
test_swap_single_case(8, 1000, 100, TestData::new(1), TestData::new(2), swap_func());
}
#[test]
fn test_apply_single() {
test_swap_single_case(8, 1000, 1000, 11, 22, apply_func());
}
#[test]
fn test_swap_many() {
test_swap_many_case(8, 10000, |v| NonZeroU32::new(v as u32).unwrap(), swap_func());
test_swap_many_case(8, 5000, |v| TestData::new(v), swap_func());
}
#[test]
fn test_apply_many() {
test_swap_many_case(8, 10000, |v| NonZeroU32::new(v as u32).unwrap(), apply_func());
}
}