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
//! # Clone only when it's necessary
//!
//! This library provides an efficient way to clone values in a rayon thread pool, but only once
//! per thread. It cuts down on computation time for potentially expensive cloning operations.
//!
//!
//! # Examples
//!
//! ```
//! use rayon_tlsctx::ThreadLocalCtx;
//! use rayon::iter::*;
//!
//! const NUM_COPIES: usize = 16;
//!
//! let mut buf: Vec<u16> = (0..!0).collect();
//!
//! // Create a thread local context with value 0.
//! let ctx = ThreadLocalCtx::new(|| {
//!     // Simulate expensive operation.
//!     // Since we are building unlocked context,
//!     // the sleeps will occur concurrently.
//!     std::thread::sleep_ms(200);
//!     0
//! });
//!
//! let pool = rayon::ThreadPoolBuilder::new().num_threads(64).build().unwrap();
//!
//! // Run inside a custom thread pool.
//! pool.install(|| {
//!     // Sum the buffer `NUM_COPIES` times and accumulate the results
//!     // into the threaded pool of counts. Note that the counts may be
//!     // Unevenly distributed.
//!     (0..NUM_COPIES)
//!         .into_par_iter()
//!         .flat_map(|_| buf.par_iter())
//!         .for_each(|i| {
//!             let mut cnt = unsafe { ctx.get() };
//!             *cnt += *i as usize;
//!         });
//! });
//!
//!
//! let buf_sum = buf.into_iter().fold(0, |acc, i| acc + i as usize);
//!
//! // What matters is that the final sum matches the expected value.
//! assert_eq!(ctx.into_iter().sum::<usize>(), buf_sum * NUM_COPIES);
//! ```

use std::cell::Cell;
use std::iter::FilterMap;
use std::ops::{Deref, DerefMut};
use std::sync::Mutex;

/// A thread local storage container for Rayon jobs
///
/// This context can be used to efficiently clone `inner`, only when it's necessary.
pub struct ThreadLocalCtx<T, F> {
    inner: F,
    init_mutex: Mutex<Vec<(Option<T>, bool)>>,
    cloned: Cell<*mut (Option<T>, bool)>,
}

unsafe impl<T, F: Send + Sync> Sync for ThreadLocalCtx<T, F> {}
unsafe impl<T, F: Send + Sync> Send for ThreadLocalCtx<T, F> {}

impl<T, F: Fn() -> T> ThreadLocalCtx<T, F> {
    /// Create a new `TlsCtx`
    ///
    /// # Examples
    ///
    /// Creating a thread-local byte buffer:
    /// ```
    /// use rayon_tlsctx::ThreadLocalCtx;
    /// let ctx = ThreadLocalCtx::new(Vec::<u8>::new);
    /// ```
    pub fn new(inner: F) -> Self {
        Self {
            inner, //: Mutex::new(inner),
            init_mutex: Mutex::new(vec![]),
            cloned: Cell::new(std::ptr::null_mut()),
        }
    }

    /// Create a new `TlsCtx`.
    ///
    /// This context utilises a lock for cloning values, making it usable for non-sync types.
    ///
    /// Cloning an initialised buffer for each thread:
    /// ```
    /// use rayon_tlsctx::ThreadLocalCtx;
    /// use rayon::iter::*;
    /// use std::cell::Cell;
    /// # use rand::prelude::*;
    /// # let mut rng = rand::thread_rng();
    ///
    /// let mut buf: Vec<u16> = (0..!0).collect();
    /// buf.shuffle(&mut rng);
    ///
    /// let buf = (buf, Cell::new(0));
    ///
    /// // Must use new_locked, because cloning a cell across threads is not allowed
    /// let ctx = ThreadLocalCtx::new_locked(move || buf.clone());
    ///
    /// (0..16).into_par_iter().for_each(|_| unsafe { ctx.get(); });
    /// ```
    pub fn new_locked(inner: F) -> ThreadLocalCtx<T, impl Fn() -> T> {
        let locked_inner = Mutex::new(inner);

        let inner = move || (locked_inner.lock().unwrap())();

        ThreadLocalCtx {
            inner,
            init_mutex: Mutex::new(vec![]),
            cloned: Cell::new(std::ptr::null_mut()),
        }
    }

    /// Get a thread local context reference with dynamically checked borrow rules
    ///
    /// # Safety
    ///
    /// Only one thread pool at a given time should use this scope. The thread pool size can not
    /// grow midway through.
    ///
    /// # Panics
    ///
    /// If called from outside of a Rayon thread pool, or when the reference is already being
    /// borrowed.
    ///
    /// # Examples
    ///
    /// ```
    /// use rayon_tlsctx::ThreadLocalCtx;
    /// use rayon::iter::*;
    ///
    /// const NUM_COPIES: usize = 16;
    ///
    /// let mut buf: Vec<u16> = (0..!0).collect();
    ///
    /// // Create a thread local context with value 0.
    /// let ctx = ThreadLocalCtx::new(|| 0);
    ///
    /// // Sum the buffer `NUM_COPIES` times and accumulate the results
    /// // into the threaded pool of counts. Note that the counts may be
    /// // Unevenly distributed.
    /// (0..NUM_COPIES)
    ///     .into_par_iter()
    ///     .flat_map(|_| buf.par_iter())
    ///     .for_each(|i| {
    ///         let mut cnt = unsafe { ctx.get() };
    ///         *cnt += *i as usize;
    ///     });
    ///
    /// let buf_sum = buf.into_iter().fold(0, |acc, i| acc + i as usize);
    ///
    /// // What matters is that the final sum matches the expected value.
    /// assert_eq!(ctx.into_iter().sum::<usize>(), buf_sum * NUM_COPIES);
    /// ```
    pub unsafe fn get<'a>(&'a self) -> ThreadLocalMut<'a, T, F> {
        if self.cloned.get().is_null() {
            let mut data = self.init_mutex.lock().unwrap();
            if self.cloned.get().is_null() {
                *data = (0..rayon::current_num_threads())
                    .map(|_| (None, false))
                    .collect();

                self.cloned.set(data.as_mut_ptr());
            }
        }

        let tid = rayon::current_thread_index().unwrap();

        match &mut *self.cloned.get().add(tid) {
            (_, true) => panic!("Already borrowed the value on thread {}!", tid),
            (Some(val), b) => {
                *b = true;
                ThreadLocalMut {
                    val,
                    parent: self,
                    tid,
                }
            }
            (val, b) => {
                *b = true;
                let cloned = (self.inner)();
                *val = Some(cloned);
                ThreadLocalMut {
                    val: val.as_mut().unwrap(),
                    parent: self,
                    tid,
                }
            }
        }
    }
}

/// Consume the context and retrieve all created items.
impl<T, F> IntoIterator for ThreadLocalCtx<T, F> {
    type Item = T;
    type IntoIter =
        FilterMap<std::vec::IntoIter<(Option<T>, bool)>, fn((Option<T>, bool)) -> Option<T>>;

    fn into_iter(self) -> Self::IntoIter {
        self.init_mutex
            .into_inner()
            .unwrap()
            .into_iter()
            .filter_map(|(i, _)| i)
    }
}

/// Borrowed thread local variable.
///
/// This structure tracks borrow rules at runtime, it may be necessary to manually
/// drop the object, if multiple rayon loops are involved.
pub struct ThreadLocalMut<'a, T, F> {
    val: &'a mut T,
    parent: &'a ThreadLocalCtx<T, F>,
    tid: usize,
}

impl<'a, T, F> Deref for ThreadLocalMut<'a, T, F> {
    type Target = T;

    fn deref(&self) -> &T {
        self.val
    }
}

impl<'a, T, F> DerefMut for ThreadLocalMut<'a, T, F> {
    fn deref_mut(&mut self) -> &mut T {
        self.val
    }
}

impl<'a, T, F> Drop for ThreadLocalMut<'a, T, F> {
    fn drop(&mut self) {
        unsafe {
            (*self.parent.cloned.get().add(self.tid)).1 = false;
        }
    }
}