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
use crossbeam::{
  epoch::{self, Atomic, Owned},
  utils::CachePadded,
};
use std::{
  cell::Cell,
  fmt,
  marker::PhantomData,
  mem, ptr,
  sync::{
    atomic::{self, Ordering},
    Arc,
  },
};

#[cfg(loom)]
pub(crate) use loom::sync::atomic::AtomicIsize;

#[cfg(not(loom))]
pub(crate) use std::sync::atomic::AtomicIsize;

// Marker flag to designate that the buffer has already been swapped
const BUFFER_SWAPPED: isize = 1 << 0;

// Designates how many bits are set aside for
const FLAGS_SHIFT: isize = 1;

// Minimum buffer capacity.
const MIN_CAP: usize = 64;
// If a buffer of at least this size is retired, thread-local garbage is flushed so that it gets
// deallocated as soon as possible.
const FLUSH_THRESHOLD_BYTES: usize = 1 << 10;

/// A buffer that holds tasks in a worker queue.
///
/// This is just a pointer to the buffer and its length - dropping an instance of this struct will
/// *not* deallocate the buffer.
struct Buffer<T> {
  /// Pointer to the allocated memory.
  ptr: *mut T,

  /// Capacity of the buffer. Always a power of two.
  cap: usize,
}

unsafe impl<T> Send for Buffer<T> {}

impl<T> Buffer<T> {
  /// Allocates a new buffer with the specified capacity.
  fn alloc(cap: usize) -> Buffer<T> {
    debug_assert_eq!(cap, cap.next_power_of_two());

    let mut v = Vec::with_capacity(cap);
    let ptr = v.as_mut_ptr();
    mem::forget(v);

    Buffer { ptr, cap }
  }

  /// Deallocates the buffer.
  unsafe fn dealloc(self) {
    drop(Vec::from_raw_parts(self.ptr, 0, self.cap));
  }

  /// Returns a pointer to the task at the specified `index`.
  unsafe fn at(&self, index: isize) -> *mut T {
    // `self.cap` is always a power of two.
    self.ptr.offset(index & (self.cap - 1) as isize)
  }

  /// Writes `task` into the specified `index`.
  unsafe fn write(&self, index: isize, task: T) {
    ptr::write_volatile(self.at(index), task)
  }
}

impl<T> Clone for Buffer<T> {
  fn clone(&self) -> Buffer<T> {
    Buffer {
      ptr: self.ptr,
      cap: self.cap,
    }
  }
}

impl<T> Copy for Buffer<T> {}

struct Inner<T> {
  slot: AtomicIsize,
  buffer: CachePadded<Atomic<Buffer<T>>>,
}

impl<T> Drop for Inner<T> {
  fn drop(&mut self) {
    let slot = self.slot.load(Ordering::Relaxed);
    let slot = slot >> FLAGS_SHIFT;

    unsafe {
      let buffer = self.buffer.load(Ordering::Relaxed, epoch::unprotected());

      // Go through the buffer from front to back and drop all tasks in the queue.
      for i in 0..slot {
        buffer.deref().at(i).drop_in_place();
      }

      // Free the memory allocated by the buffer.
      buffer.into_owned().into_box().dealloc();
    }
  }
}

/// A worker queue.
///
/// This is a queue that is owned by a single thread, but other threads may steal the entire underlying buffer. Typically one would use a single worker queue per thread.
///
/// # Examples
///
/// ```
/// use swap_queue::Worker;
///
/// let w = Worker::new();
/// let s = w.stealer();
///
/// w.push(1);
/// w.push(2);
/// w.push(3);
///
/// assert_eq!(s.take_queue(), vec![1, 2, 3]);
/// w.push(4);
/// w.push(5);
/// w.push(6);
/// assert_eq!(s.take_queue(), vec![4, 5, 6]);
/// ```

pub struct Worker<T> {
  /// A reference to the inner representation of the queue.
  inner: Arc<CachePadded<Inner<T>>>,
  /// A copy of `inner.buffer` for quick access.
  buffer: Cell<Buffer<T>>,
  /// Indicates that the worker cannot be shared among threads.
  _marker: PhantomData<*mut ()>,
}

unsafe impl<T: Send> Send for Worker<T> {}

impl<T> Worker<T> {
  /// Creates a new Worker queue.
  ///
  /// Tasks are pushed and the underlying buffer is swapped and converted back into a `Vec<T>` when taken by a stealer.
  ///
  /// # Examples
  ///
  /// ```
  /// use swap_queue::Worker;
  ///
  /// let w = Worker::<i32>::new();
  /// ```
  pub fn new() -> Worker<T> {
    let buffer = Buffer::alloc(MIN_CAP);

    let inner = Arc::new(CachePadded::new(Inner {
      slot: AtomicIsize::new(0),
      buffer: CachePadded::new(Atomic::new(buffer)),
    }));

    Worker {
      inner,
      buffer: Cell::new(buffer),
      _marker: PhantomData,
    }
  }

  /// Creates a stealer for this queue.
  ///
  /// The returned stealer can be shared among threads and cloned.
  ///
  /// # Examples
  ///
  /// ```
  /// use swap_queue::Worker;
  ///
  /// let w = Worker::<i32>::new();
  /// let s = w.stealer();
  /// ```
  pub fn stealer(&self) -> Stealer<T> {
    Stealer {
      inner: self.inner.clone(),
    }
  }

  /// Resizes the internal buffer to the new capacity of `new_cap`.
  #[cold]
  unsafe fn resize(&self, new_cap: usize) {
    let slot = self.inner.slot.load(Ordering::Relaxed);
    let slot = slot >> FLAGS_SHIFT;

    let guard = &epoch::pin();

    let buffer = self
      .inner
      .buffer
      .load(Ordering::Relaxed, guard)
      .as_ref()
      .unwrap();

    // Allocate a new buffer and copy data from the old buffer to the new one.
    let new = Buffer::alloc(new_cap);
    for i in 0..slot {
      ptr::copy_nonoverlapping(buffer.at(i), new.at(i), 1);
    }

    let guard = &epoch::pin();

    self.buffer.replace(new);

    let old = self
      .inner
      .buffer
      .swap(Owned::new(new).into_shared(guard), Ordering::Release, guard);

    // Destroy the old buffer later.
    guard.defer_unchecked(move || old.into_owned().into_box().dealloc());

    // If the buffer is very large, then flush the thread-local garbage in order to deallocate
    // it as soon as possible.
    if mem::size_of::<T>() * new_cap >= FLUSH_THRESHOLD_BYTES {
      guard.flush();
    }
  }

  /// Push a task to the queue and returns the index written to
  pub fn push(&self, task: T) -> isize {
    let slot = self
      .inner
      .slot
      .fetch_add(1 << FLAGS_SHIFT, Ordering::Relaxed);

    if slot & BUFFER_SWAPPED == BUFFER_SWAPPED {
      let buffer = Buffer::alloc(MIN_CAP);
      self.buffer.replace(buffer);
      let guard = &epoch::pin();
      let old = self.inner.buffer.swap(
        Owned::new(buffer).into_shared(guard),
        Ordering::Release,
        guard,
      );

      unsafe {
        // Destroy the old buffer later.
        guard.defer_unchecked(move || old.into_owned().into_box().dealloc());
      }

      atomic::fence(Ordering::Release);

      self.inner.slot.store(1 << FLAGS_SHIFT, Ordering::Relaxed);

      // Write `task` into the slot.
      unsafe {
        buffer.write(0, task);
      }

      0
    } else {
      let slot = slot >> FLAGS_SHIFT;
      let mut buffer = self.buffer.get();

      // Is the queue full?
      if slot >= buffer.cap as isize {
        // Yes. Grow the underlying buffer.
        unsafe {
          self.resize(2 * buffer.cap);
        }

        buffer = self.buffer.get();
      }

      // Write `task` into the slot.
      unsafe {
        buffer.write(slot, task);
      }

      slot
    }
  }
}

impl<T> fmt::Debug for Worker<T> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.pad("Worker { .. }")
  }
}
pub struct Stealer<T> {
  /// A reference to the inner representation of the queue.
  inner: Arc<CachePadded<Inner<T>>>,
}

unsafe impl<T: Send> Send for Stealer<T> {}
unsafe impl<T: Send> Sync for Stealer<T> {}

impl<T> Stealer<T> {
  /// Take the entire queue via swapping the underlying buffer and converting into a `Vec<T>`
  pub fn take_queue(&self) -> Vec<T> {
    let slot = self.inner.slot.fetch_or(BUFFER_SWAPPED, Ordering::Relaxed);

    // Buffer was previously taken
    if slot & BUFFER_SWAPPED == BUFFER_SWAPPED {
      return vec![];
    }

    let slot = slot >> FLAGS_SHIFT;

    let new = Buffer::alloc(MIN_CAP);

    let guard = &epoch::pin();

    let old = unsafe {
      self
        .inner
        .buffer
        .swap(Owned::new(new).into_shared(guard), Ordering::Release, guard)
        .into_owned()
    };

    unsafe { Vec::from_raw_parts(old.ptr, slot as usize, old.cap) }
  }
}

impl<T> Clone for Stealer<T> {
  fn clone(&self) -> Stealer<T> {
    Stealer {
      inner: self.inner.clone(),
    }
  }
}

impl<T> fmt::Debug for Stealer<T> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.pad("Stealer { .. }")
  }
}

#[cfg(all(loom, test))]
mod concurrent_tests {
  use super::*;
  use loom::thread;
  use std::convert::identity;

  #[test]
  fn test_concurrent_logic() {
    loom::model(|| {
      let queue = Worker::new();
      let stealer = queue.stealer();

      for i in 0..300 {
        queue.push(i);
      }

      thread::spawn(move || {
        let batch = stealer.take_queue();
        let expected = (0..300).map(identity).collect::<Vec<i32>>();
        assert_eq!(batch, expected);
      });
    });
  }
}