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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
use std::cell::UnsafeCell;
use std::sync::{Mutex,MutexGuard,TryLockError, Arc};
use std::sync::atomic::{AtomicUsize,fence, spin_loop_hint};
use std::sync::atomic::Ordering::{SeqCst,Relaxed};
use std::thread::yield_now;
use std::{ptr, mem};
use std::ops::{Deref,DerefMut};
use std::fmt::{self, Debug,Display};
use std::error::Error;
const MAX_UPDATE_SPINS: usize = 7;
pub struct PairLock<T> {
reads_active: AtomicUsize,
finished_reads: [AtomicUsize; 2],
values: [UnsafeCell<T>; 2],
inactive_reads: Mutex<usize>,
}
unsafe impl<T:Send> Send for PairLock<T> {}
unsafe impl<T:Send+Sync> Sync for PairLock<T> {}
impl<T> PairLock<T> {
pub fn new(active: T, inactive: T) -> Self {
PairLock {
reads_active: AtomicUsize::new(0),
finished_reads: [AtomicUsize::new(0), AtomicUsize::new(!0)],
values: [UnsafeCell::new(active), UnsafeCell::new(inactive)],
inactive_reads: Mutex::new(!0),
}
}
pub fn with_default(init: T) -> Self where T: Default {
Self::new(init, T::default())
}
pub fn with_clone(init: T) -> Self where T: Clone {
let second = init.clone();
Self::new(init, second)
}
pub fn view<F:FnOnce(&T)->R,R>(&self, viewer: F) -> R {
unsafe {
let active = self.reads_active.fetch_add(2, SeqCst);
let slot = active & 1;
struct Releaser<'a>(&'a AtomicUsize);
impl<'a> Drop for Releaser<'a> {
fn drop(&mut self) {
fence(SeqCst);
self.0.fetch_add(2, Relaxed);
}
}
let _defer = Releaser(&self.finished_reads[slot]);
viewer(&*self.values[slot].get())
}
}
pub fn get_clone(&self) -> T where T: Clone {
self.view(|v| v.clone() )
}
unsafe fn check_inactive<'a>(&'a self, inactive_reads: MutexGuard<'a,usize>)
-> Result<UpdateGuard<'a,T>, MutexGuard<'a,usize>> {
let slot = *inactive_reads & 1;
if self.finished_reads[slot].load(Relaxed) == *inactive_reads {
fence(SeqCst);
Ok(UpdateGuard{ guard: inactive_reads, pl: self })
} else {
Err(inactive_reads)
}
}
pub fn update(&self) -> UpdateGuard<T> {
loop {
unsafe {
let mut inactive_reads = self.inactive_reads.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner() );
for _ in 0..MAX_UPDATE_SPINS {
inactive_reads = match self.check_inactive(inactive_reads) {
Ok(success) => return success,
Err(retry) => retry
};
spin_loop_hint();
}
drop(inactive_reads);
}
yield_now();
}
}
pub fn try_update(&self) -> Result<UpdateGuard<T>,TryUpdateError> {
unsafe {
let guard = match self.inactive_reads.try_lock() {
Ok(guard) => guard,
Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),
Err(TryLockError::WouldBlock) => return Err(TryUpdateError::OtherUpdate)
};
self.check_inactive(guard).map_err(|_| TryUpdateError::InactiveReads )
}
}
pub fn set(&self, value: T) -> T {
mem::replace(&mut*self.update(), value)
}
pub fn into_inner(self) -> (T, T) {
let PairLock{ reads_active, values, .. } = self;
let active = reads_active.into_inner() & 1;
unsafe {
let active_ = ptr::read(values[active].get());
let inactive_ = ptr::read(values[active^1].get());
mem::forget(values);
(active_, inactive_)
}
}
pub fn get_mut_both(&mut self) -> (&mut T, &mut T) {
let active = *self.reads_active.get_mut() & 1;
unsafe {
(&mut*self.values[active].get(), &mut*self.values[active^1].get())
}
}
pub fn get_mut_active(&mut self) -> &mut T {
self.get_mut_both().0
}
pub fn get_mut_inactive(&mut self) -> &mut T {
self.get_mut_both().1
}
}
impl<T> PairLock<Arc<T>> {
pub fn new_arc(value: T) -> Self {
PairLock::with_clone(Arc::new(value))
}
}
impl<T:?Sized> PairLock<Arc<T>> {
pub fn get(&self) -> Arc<T> {
self.get_clone()
}
}
impl<T:Copy> PairLock<T> {
pub fn read(&self) -> T {
self.get_clone()
}
}
impl<T:Debug> Debug for PairLock<T> {
fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
struct Hidden;
impl Debug for Hidden {
fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
fmtr.write_str("_")
}
}
self.view(|v| {
fmtr.debug_tuple("PairLock")
.field(v)
.field(&Hidden)
.finish()
})
}
}
impl<T:Default> Default for PairLock<T> {
fn default() -> Self {
Self::new(T::default(), T::default())
}
}
impl<T:Clone> Clone for PairLock<T> {
fn clone(&self) -> Self {
Self::new(self.get_clone(), self.get_clone())
}
fn clone_from(&mut self, source: &Self) {
let (a,b) = unsafe {
(&mut*self.values[0].get(), &mut*self.values[1].get())
};
source.view(|init| a.clone_from(init) );
b.clone_from(&*a);
}
}
pub struct UpdateGuard<'a, T:'a> {
guard: MutexGuard<'a, usize>,
pl: &'a PairLock<T>,
}
impl<'a,T> Drop for UpdateGuard<'a,T> {
fn drop(&mut self) {
let inactive_reads = *self.guard;
fence(SeqCst);
let active_reads = self.pl.reads_active.swap(inactive_reads, SeqCst);
*self.guard = active_reads;
}
}
impl<'a,T> Deref for UpdateGuard<'a,T> {
type Target = T;
fn deref(&self) -> &T {
unsafe {
let slot = *self.guard & 1;
&*self.pl.values[slot].get()
}
}
}
impl<'a,T> DerefMut for UpdateGuard<'a,T> {
fn deref_mut(&mut self) -> &mut T {
unsafe {
let slot = *self.guard & 1;
&mut*self.pl.values[slot].get()
}
}
}
impl<'a,T> UpdateGuard<'a,T> {
pub fn active(this: &Self) -> &T {
unsafe {
let other_slot = (!*this.guard) & 1;
&*this.pl.values[other_slot].get()
}
}
pub fn both(this: &mut Self) -> (&mut T, &T) {
unsafe {
let slot = *this.guard & 1;
let values = &this.pl.values;
(&mut*values[slot].get(), &*values[slot^1].get())
}
}
pub fn cancel(this: Self) {
unsafe {
let guard = ptr::read(&this.guard);
mem::forget(this);
drop(guard);
}
}
}
impl<'a, T:Debug> Debug for UpdateGuard<'a,T> {
fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
fmtr.debug_struct("UpdateGuard")
.field("mutable", &*self)
.field("active", &*UpdateGuard::active(self))
.finish()
}
}
impl<'a,T> PartialEq for UpdateGuard<'a,T> {
fn eq(&self, other: &Self) -> bool {
ptr::eq(self, other)
}
}
#[derive(Clone,Copy, PartialEq,Eq)]
pub enum TryUpdateError {
OtherUpdate,
InactiveReads,
}
impl Error for TryUpdateError {
fn description(&self) -> &'static str {
match *self {
TryUpdateError::OtherUpdate => "locked by another update",
TryUpdateError::InactiveReads => "unfinished reads of the inactive value",
}
}
}
impl Display for TryUpdateError {
fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
fmtr.write_str(self.description())
}
}
impl Debug for TryUpdateError {
fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(self, fmtr)
}
}