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
//! This crate aims, like many others, to get rid of the pesky `'a` in your
//! guards, while keeping the easy to reason about semantics of
//! read-write-locks.
//!
//! The trick is based on a finite set of static `RwLock`s, which are mapped to
//! the memory adress of a container type implementing `StableDeref`, from the
//! `stable_deref` crate.
#![deny(missing_docs)]
#[macro_use]
extern crate lazy_static;
extern crate parking_lot;
extern crate stable_deref_trait;

use std::{mem, ptr};
use std::cell::UnsafeCell;
use std::thread::{self, ThreadId};
use std::ops::{Deref, DerefMut};
use std::fmt::{self};

use parking_lot::{RwLock, RwLockReadGuard};
use stable_deref_trait::StableDeref;

const N_LOCKS: usize = 1024;

enum State {
    Shared,
    ThreadExclusive(ThreadId),
}

lazy_static! {
    static ref LOCKS: [RwLock<State>; N_LOCKS] = {
        let mut locks: [RwLock<State>; N_LOCKS] = unsafe { mem::uninitialized() };
        for i in 0..N_LOCKS {
            unsafe {
                ptr::write(&mut locks[i], RwLock::new(State::Shared))
            }
        }
        locks
    };
}

/// A wrapper type providing run-time shared ord thread-local exclusive access
/// to an inner value of type `T`,
/// where `T` implements `StableDeref`
pub struct Thex<T> {
    cell: UnsafeCell<T>,
}

impl<T: StableDeref + fmt::Debug> fmt::Debug for Thex<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let _guard = self.shared();
        unsafe { write!(f, "Thex({:?})", &*self.cell.get()) }
    }
}

impl<T: Clone + std::fmt::Debug + StableDeref> Clone for Thex<T> {
    fn clone(&self) -> Self {
        // secure readlock
        let _guard = self.shared();
        unsafe {
            Thex {
                cell: UnsafeCell::new((*self.cell.get()).clone()),
            }
        }
    }
}

unsafe impl<T> Sync for Thex<T> {}
unsafe impl<T> Send for Thex<T> {}

#[inline]
// select a lock based on the memory address of `T`
//
// shift right, because pointers usually have their least significant
// bits set to zero
fn lock_nr<T>(ptr: *const T) -> usize {
    (ptr as usize >> 4) % N_LOCKS
}

/// A guard guaranteeing that no writes are made while it is held
pub struct Shared<T> {
    value: *const T,
    _guard: RwLockReadGuard<'static, State>,
}

/// A guard guaranteeing thread-local exclusivity while it is held
pub struct Exclusive<T> {
    value: *mut T,
    _guard: RwLockReadGuard<'static, State>,
}

impl<T> Deref for Shared<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        unsafe { &*self.value }
    }
}

impl<T> Deref for Exclusive<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        unsafe { &*self.value }
    }
}

impl<T> DerefMut for Exclusive<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { &mut *self.value }
    }
}

impl<T: StableDeref> Thex<T> {
    /// Construct a new wrapped value
    pub fn new(t: T) -> Self {
        Thex {
            cell: UnsafeCell::new(t),
        }
    }

    /// Aquire a read-only shared reference to the contained `T`
    pub fn shared(&self) -> Shared<T> {
        let t_ref = self.cell.get() as *const T;
        let lock = lock_nr(t_ref);
        {
            let read = LOCKS[lock].read();

            match *read {
                State::Shared => {
                    return Shared {
                        value: t_ref,
                        _guard: read,
                    }
                }
                _ => (),
            }
        }

        let mut write = LOCKS[lock].write();
        *write = State::Shared;

        return Shared {
            value: t_ref,
            _guard: write.downgrade(),
        };
    }

    /// Returns a thread-exclusive lock to the wrapped value
    ///
    /// # Unsafety
    /// It is unsafe to use this function, since you could easily
    /// alias the same value multiple times from the same thread.
    ///
    /// If you want a safe alternative, you can use `shared` and wrap
    /// the value in a `RefCell`
    pub unsafe fn exclusive(&self) -> Exclusive<T> {
        loop {
            let t_ref = self.cell.get() as *mut T;
            let lock = lock_nr(t_ref);
            {
                let read = LOCKS[lock].read();
                let mut exclusive = false;
                match *read {
                    State::ThreadExclusive(ref thread_id) => {
                        if thread_id == &thread::current().id() {
                            exclusive = true;
                        }
                    }
                    _ => (),
                }
                // can't wait for nll
                if exclusive {
                    // check if pointer did not change in the meantime
                    return Exclusive {
                        value: t_ref,
                        _guard: read,
                    };
                }
            }
            let mut write = LOCKS[lock].write();
            *write = State::ThreadExclusive(thread::current().id());
            // here we still have exclusive access to our unsafecell wrapped arc

            let read = write.downgrade();

            return Exclusive {
                value: t_ref,
                _guard: read,
            };
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;
    use std::rc::Rc;
    use std::sync::Arc;

    #[test]
    fn boxes() {
        let n = 10_000;
        let mut thexes = vec![];
        let mut handles = vec![];

        for _ in 0..n {
            thexes.push(Thex::new(Box::new(0)));
        }

        let n_threads = 100;

        let wrapped = Arc::new(thexes);

        for _ in 0..n_threads {
            let wrapped = wrapped.clone();
            handles.push(thread::spawn(move || {
                for n in wrapped.iter() {
                    unsafe { **n.exclusive() += 1; }
                }
            }))
        }

        for handle in handles {
            handle.join().unwrap()
        }

        for n in wrapped.iter() {
            assert_eq!(**n.shared(), n_threads);
        }
    }


    #[test]
    fn rc() {
        let n = 100_000;
        let mut thexes = vec![];
        let mut handles = vec![];

        for _ in 0..n {
            thexes.push(Thex::new(Rc::new(0)));
        }

        let n_threads = 16;

        let wrapped = Arc::new(thexes);

        for _ in 0..n_threads {
            let wrapped = wrapped.clone();
            handles.push(thread::spawn(move || {
                for n in wrapped.iter() {
                    unsafe { *Rc::make_mut(&mut *n.exclusive() ) += 1; }
                }
            }))
        }

        for handle in handles.drain(..) {
            handle.join().unwrap()
        }

        for n in wrapped.iter() {
            assert_eq!(**n.shared(), n_threads);
        }

        let wrapped2 = Arc::new((*wrapped).clone());

        let mut handles2 = vec![];

        for _ in 0..n_threads {
            let wrapped = wrapped2.clone();
            handles2.push(thread::spawn(move || {
                for n in wrapped.iter() {
                    unsafe { *Rc::make_mut(&mut *n.exclusive()) += 1; }
                }
            }))
        }

        for handle in handles2.drain(..) {
            handle.join().unwrap()
        }

        for n in wrapped.iter() {
            assert_eq!(**n.shared(), n_threads);
        }

        for n in wrapped2.iter() {
            assert_eq!(**n.shared(), n_threads * 2);
        }
    }
}