-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
atomics.rs
236 lines (191 loc) · 5.73 KB
/
atomics.rs
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
use crate::sync::arcunique::ArcUnique;
use anyhow::*;
use std::convert::TryFrom;
use std::ops::Deref;
use std::sync::atomic::{AtomicPtr, Ordering};
use std::sync::Arc;
/// AtomicBox<T> is a safe wrapper around AtomicPtr<T>
#[derive(Debug)]
pub struct AtomicBox<T: Sized> {
ptr: AtomicPtr<T>,
}
impl<T: Sized> AtomicBox<T> {
///
/// Allocates a new AtomicBox containing the given value
pub fn new(value: T) -> AtomicBox<T> {
AtomicBox {
ptr: AtomicPtr::new(AtomicBox::alloc_from(value)),
}
}
#[inline]
fn alloc_from(value: T) -> *mut T {
let total: Arc<T> = Arc::new(value);
Arc::into_raw(total) as *mut T
}
fn compare_and_swap(&self, current: *mut T, new: *mut T, order: Ordering) -> *mut T {
self.ptr.compare_and_swap(current, new, order)
}
fn take(&self) -> Arc<T> {
loop {
let curr = self.ptr.load(Ordering::Acquire);
let null: *mut T = std::ptr::null_mut();
if curr == null {
continue;
}
if self.compare_and_swap(curr, null, Ordering::AcqRel) == curr {
return unsafe { Arc::from_raw(curr) };
}
}
}
fn release(&self, ptr: *mut T) {
self.ptr.store(ptr, Ordering::Release);
}
///
/// Get inner value
pub fn get(&self) -> Arc<T> {
let val = self.take();
let copy = Arc::clone(&val);
let ptr = Arc::into_raw(val) as *mut T;
self.release(ptr);
copy
}
///
/// Extract mutable pointer of the contained value
pub fn extract_mut_ptr(&mut self) -> *mut T {
let x = self.get();
Arc::into_raw(x) as *mut T
}
///
/// If possible, extract inner value into unique Arc
pub fn extract(&self) -> Result<Arc<T>> {
let au: ArcUnique<Arc<T>> = ArcUnique::try_from(self.get())?;
Ok(au.deref().clone())
}
///
/// Atomically replace the inner value with the result of applying the
/// given closure to the current value
pub fn replace_with<F>(&self, f: F)
where
F: Fn(Arc<T>) -> T,
{
let val = self.take();
let new_val = f(val);
let ptr = Arc::into_raw(Arc::new(new_val)) as *mut T;
self.release(ptr);
}
}
impl<T: Sized + PartialEq> PartialEq for AtomicBox<T> {
fn eq(&self, other: &AtomicBox<T>) -> bool {
self == other
}
}
impl<T: Sized> Drop for AtomicBox<T> {
fn drop(&mut self) {
unsafe { Arc::from_raw(self.ptr.load(Ordering::Acquire)) };
}
}
unsafe impl<T: Sized> Sync for AtomicBox<T> {}
unsafe impl<T: Sized> Send for AtomicBox<T> {}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Barrier};
use std::thread;
use super::AtomicBox;
#[test]
#[cfg_attr(miri, ignore)]
fn atomic_arc_new() {
let b = AtomicBox::new(1024);
assert_eq!(*b.get(), 1024);
}
#[test]
#[cfg_attr(miri, ignore)]
fn atomic_arc_replace_with() {
let value: i64 = 1024;
let b = AtomicBox::new(value);
b.replace_with(|x| *x * 2);
assert_eq!(*b.get(), value * 2);
}
#[test]
#[cfg_attr(miri, ignore)]
fn atomic_arc_replace_with_ten_times() {
let value = 1024;
let b = AtomicBox::new(value);
for _i in 0..10 {
b.replace_with(|x| *x * 2);
}
assert_eq!(*b.get(), value * 2_i32.pow(10));
}
#[test]
#[cfg_attr(miri, ignore)]
fn atomic_arc_replace_instance() {
let b = Arc::new(AtomicBox::new(1024));
let b1 = b.clone();
b1.replace_with(|x| *x * 2);
assert_eq!(*b.get(), 2048);
}
#[test]
#[cfg_attr(miri, ignore)]
fn atomic_arc_threaded_leak_test() {
let val = Arc::new(AtomicBox::new(10));
let val_cpys: Vec<Arc<AtomicBox<i32>>> = (0..10).map(|_| val.clone()).collect();
let mut guards = Vec::new();
for i in 0..10 {
let val_cpy = val_cpys[i].clone();
let guard = thread::spawn(move || {
val_cpy.replace_with(|x| *x * 2);
});
guards.push(guard);
}
for g in guards {
g.join().unwrap();
}
assert_eq!(*val.get(), 10 * 2_i32.pow(10));
}
#[test]
#[cfg_attr(miri, ignore)]
fn atomic_arc_threaded_contention() {
let abox = Arc::new(AtomicBox::new(0));
let thread_num = 10;
let mut guards = Vec::new();
let barrier = Arc::new(Barrier::new(thread_num));
for _i in 0..thread_num {
let b = Arc::clone(&barrier);
let cpy = abox.clone();
guards.push(thread::spawn(move || {
b.wait();
for _j in 0..1000 {
cpy.replace_with(|x| *x + 100)
}
}));
}
for g in guards {
g.join().unwrap();
}
assert_eq!(*abox.get(), thread_num * 1000 * 100);
}
#[test]
#[cfg_attr(miri, ignore)]
fn atomic_arc_vector_container() {
let values: Vec<i32> = (0..10).map(|x: i32| x.pow(2)).collect();
let abox = Arc::new(AtomicBox::new(vec![]));
let mut guards = Vec::new();
for i in 0..10 {
let cpy = abox.clone();
let values: Vec<i32> = values.clone();
guards.push(thread::spawn(move || {
cpy.replace_with(|x| {
let mut nx = (*x).clone();
nx.push(values[i]);
nx
})
}));
}
for g in guards {
g.join().unwrap();
}
assert_eq!(abox.get().len(), values.len());
for i in values {
assert_eq!(abox.get().contains(&i), true);
}
}
}