Debian Codegraph @

third_party/rust/crossbeam-deque/src/deque.rs

raw
1 use std::cell::{Cell, UnsafeCell};
2 use std::cmp;
3 use std::fmt;
4 use std::iter::FromIterator;
5 use std::marker::PhantomData;
6 use std::mem::{self, ManuallyDrop, MaybeUninit};
7 use std::ptr;
8 use std::sync::atomic::{self, AtomicIsize, AtomicPtr, AtomicUsize, Ordering};
9 use std::sync::Arc;
10
11 use crate::epoch::{self, Atomic, Owned};
12 use crate::utils::{Backoff, CachePadded};
13
14 // Minimum buffer capacity.
15 const MIN_CAP: usize = 64;
16 // Maximum number of tasks that can be stolen in `steal_batch()` and `steal_batch_and_pop()`.
17 const MAX_BATCH: usize = 32;
18 // If a buffer of at least this size is retired, thread-local garbage is flushed so that it gets
19 // deallocated as soon as possible.
20 const FLUSH_THRESHOLD_BYTES: usize = 1 << 10;
21
22 /// A buffer that holds tasks in a worker queue.
23 ///
24 /// This is just a pointer to the buffer and its length - dropping an instance of this struct will
25 /// *not* deallocate the buffer.
26 struct Buffer<T> {
27 /// Pointer to the allocated memory.
28 ptr: *mut T,
29
30 /// Capacity of the buffer. Always a power of two.
31 cap: usize,
32 }
33
34 unsafe impl<T> Send for Buffer<T> {}
35
36 impl<T> Buffer<T> {
37 /// Allocates a new buffer with the specified capacity.
38 fn alloc(cap: usize) -> Buffer<T> {
39 debug_assert_eq!(cap, cap.next_power_of_two());
40
41 let mut v = ManuallyDrop::new(Vec::with_capacity(cap));
42 let ptr = v.as_mut_ptr();
43
44 Buffer { ptr, cap }
45 }
46
47 /// Deallocates the buffer.
48 unsafe fn dealloc(self) {
49 drop(Vec::from_raw_parts(self.ptr, 0, self.cap));
50 }
51
52 /// Returns a pointer to the task at the specified `index`.
53 unsafe fn at(&self, index: isize) -> *mut T {
54 // `self.cap` is always a power of two.
55 // We do all the loads at `MaybeUninit` because we might realize, after loading, that we
56 // don't actually have the right to access this memory.
57 self.ptr.offset(index & (self.cap - 1) as isize)
58 }
59
60 /// Writes `task` into the specified `index`.
61 ///
62 /// This method might be concurrently called with another `read` at the same index, which is
63 /// technically speaking a data race and therefore UB. We should use an atomic store here, but
64 /// that would be more expensive and difficult to implement generically for all types `T`.
65 /// Hence, as a hack, we use a volatile write instead.
66 unsafe fn write(&self, index: isize, task: MaybeUninit<T>) {
67 ptr::write_volatile(self.at(index).cast::<MaybeUninit<T>>(), task)
68 }
69
70 /// Reads a task from the specified `index`.
71 ///
72 /// This method might be concurrently called with another `write` at the same index, which is
73 /// technically speaking a data race and therefore UB. We should use an atomic load here, but
74 /// that would be more expensive and difficult to implement generically for all types `T`.
75 /// Hence, as a hack, we use a volatile load instead.
76 unsafe fn read(&self, index: isize) -> MaybeUninit<T> {
77 ptr::read_volatile(self.at(index).cast::<MaybeUninit<T>>())
78 }
79 }
80
81 impl<T> Clone for Buffer<T> {
82 fn clone(&self) -> Buffer<T> {
83 Buffer {
84 ptr: self.ptr,
85 cap: self.cap,
86 }
87 }
88 }
89
90 impl<T> Copy for Buffer<T> {}
91
92 /// Internal queue data shared between the worker and stealers.
93 ///
94 /// The implementation is based on the following work:
95 ///
96 /// 1. [Chase and Lev. Dynamic circular work-stealing deque. SPAA 2005.][chase-lev]
97 /// 2. [Le, Pop, Cohen, and Nardelli. Correct and efficient work-stealing for weak memory models.
98 /// PPoPP 2013.][weak-mem]
99 /// 3. [Norris and Demsky. CDSchecker: checking concurrent data structures written with C/C++
100 /// atomics. OOPSLA 2013.][checker]
101 ///
102 /// [chase-lev]: https://dl.acm.org/citation.cfm?id=1073974
103 /// [weak-mem]: https://dl.acm.org/citation.cfm?id=2442524
104 /// [checker]: https://dl.acm.org/citation.cfm?id=2509514
105 struct Inner<T> {
106 /// The front index.
107 front: AtomicIsize,
108
109 /// The back index.
110 back: AtomicIsize,
111
112 /// The underlying buffer.
113 buffer: CachePadded<Atomic<Buffer<T>>>,
114 }
115
116 impl<T> Drop for Inner<T> {
117 fn drop(&mut self) {
118 // Load the back index, front index, and buffer.
119 let b = *self.back.get_mut();
120 let f = *self.front.get_mut();
121
122 unsafe {
123 let buffer = self.buffer.load(Ordering::Relaxed, epoch::unprotected());
124
125 // Go through the buffer from front to back and drop all tasks in the queue.
126 let mut i = f;
127 while i != b {
128 buffer.deref().at(i).drop_in_place();
129 i = i.wrapping_add(1);
130 }
131
132 // Free the memory allocated by the buffer.
133 buffer.into_owned().into_box().dealloc();
134 }
135 }
136 }
137
138 /// Worker queue flavor: FIFO or LIFO.
139 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
140 enum Flavor {
141 /// The first-in first-out flavor.
142 Fifo,
143
144 /// The last-in first-out flavor.
145 Lifo,
146 }
147
148 /// A worker queue.
149 ///
150 /// This is a FIFO or LIFO queue that is owned by a single thread, but other threads may steal
151 /// tasks from it. Task schedulers typically create a single worker queue per thread.
152 ///
153 /// # Examples
154 ///
155 /// A FIFO worker:
156 ///
157 /// ```
158 /// use crossbeam_deque::{Steal, Worker};
159 ///
160 /// let w = Worker::new_fifo();
161 /// let s = w.stealer();
162 ///
163 /// w.push(1);
164 /// w.push(2);
165 /// w.push(3);
166 ///
167 /// assert_eq!(s.steal(), Steal::Success(1));
168 /// assert_eq!(w.pop(), Some(2));
169 /// assert_eq!(w.pop(), Some(3));
170 /// ```
171 ///
172 /// A LIFO worker:
173 ///
174 /// ```
175 /// use crossbeam_deque::{Steal, Worker};
176 ///
177 /// let w = Worker::new_lifo();
178 /// let s = w.stealer();
179 ///
180 /// w.push(1);
181 /// w.push(2);
182 /// w.push(3);
183 ///
184 /// assert_eq!(s.steal(), Steal::Success(1));
185 /// assert_eq!(w.pop(), Some(3));
186 /// assert_eq!(w.pop(), Some(2));
187 /// ```
188 pub struct Worker<T> {
189 /// A reference to the inner representation of the queue.
190 inner: Arc<CachePadded<Inner<T>>>,
191
192 /// A copy of `inner.buffer` for quick access.
193 buffer: Cell<Buffer<T>>,
194
195 /// The flavor of the queue.
196 flavor: Flavor,
197
198 /// Indicates that the worker cannot be shared among threads.
199 _marker: PhantomData<*mut ()>, // !Send + !Sync
200 }
201
202 unsafe impl<T: Send> Send for Worker<T> {}
203
204 impl<T> Worker<T> {
205 /// Creates a FIFO worker queue.
206 ///
207 /// Tasks are pushed and popped from opposite ends.
208 ///
209 /// # Examples
210 ///
211 /// ```
212 /// use crossbeam_deque::Worker;
213 ///
214 /// let w = Worker::<i32>::new_fifo();
215 /// ```
216 pub fn new_fifo() -> Worker<T> {
217 let buffer = Buffer::alloc(MIN_CAP);
218
219 let inner = Arc::new(CachePadded::new(Inner {
220 front: AtomicIsize::new(0),
221 back: AtomicIsize::new(0),
222 buffer: CachePadded::new(Atomic::new(buffer)),
223 }));
224
225 Worker {
226 inner,
227 buffer: Cell::new(buffer),
228 flavor: Flavor::Fifo,
229 _marker: PhantomData,
230 }
231 }
232
233 /// Creates a LIFO worker queue.
234 ///
235 /// Tasks are pushed and popped from the same end.
236 ///
237 /// # Examples
238 ///
239 /// ```
240 /// use crossbeam_deque::Worker;
241 ///
242 /// let w = Worker::<i32>::new_lifo();
243 /// ```
244 pub fn new_lifo() -> Worker<T> {
245 let buffer = Buffer::alloc(MIN_CAP);
246
247 let inner = Arc::new(CachePadded::new(Inner {
248 front: AtomicIsize::new(0),
249 back: AtomicIsize::new(0),
250 buffer: CachePadded::new(Atomic::new(buffer)),
251 }));
252
253 Worker {
254 inner,
255 buffer: Cell::new(buffer),
256 flavor: Flavor::Lifo,
257 _marker: PhantomData,
258 }
259 }
260
261 /// Creates a stealer for this queue.
262 ///
263 /// The returned stealer can be shared among threads and cloned.
264 ///
265 /// # Examples
266 ///
267 /// ```
268 /// use crossbeam_deque::Worker;
269 ///
270 /// let w = Worker::<i32>::new_lifo();
271 /// let s = w.stealer();
272 /// ```
273 pub fn stealer(&self) -> Stealer<T> {
274 Stealer {
275 inner: self.inner.clone(),
276 flavor: self.flavor,
277 }
278 }
279
280 /// Resizes the internal buffer to the new capacity of `new_cap`.
281 #[cold]
282 unsafe fn resize(&self, new_cap: usize) {
283 // Load the back index, front index, and buffer.
284 let b = self.inner.back.load(Ordering::Relaxed);
285 let f = self.inner.front.load(Ordering::Relaxed);
286 let buffer = self.buffer.get();
287
288 // Allocate a new buffer and copy data from the old buffer to the new one.
289 let new = Buffer::alloc(new_cap);
290 let mut i = f;
291 while i != b {
292 ptr::copy_nonoverlapping(buffer.at(i), new.at(i), 1);
293 i = i.wrapping_add(1);
294 }
295
296 let guard = &epoch::pin();
297
298 // Replace the old buffer with the new one.
299 self.buffer.replace(new);
300 let old =
301 self.inner
302 .buffer
303 .swap(Owned::new(new).into_shared(guard), Ordering::Release, guard);
304
305 // Destroy the old buffer later.
306 guard.defer_unchecked(move || old.into_owned().into_box().dealloc());
307
308 // If the buffer is very large, then flush the thread-local garbage in order to deallocate
309 // it as soon as possible.
310 if mem::size_of::<T>() * new_cap >= FLUSH_THRESHOLD_BYTES {
311 guard.flush();
312 }
313 }
314
315 /// Reserves enough capacity so that `reserve_cap` tasks can be pushed without growing the
316 /// buffer.
317 fn reserve(&self, reserve_cap: usize) {
318 if reserve_cap > 0 {
319 // Compute the current length.
320 let b = self.inner.back.load(Ordering::Relaxed);
321 let f = self.inner.front.load(Ordering::SeqCst);
322 let len = b.wrapping_sub(f) as usize;
323
324 // The current capacity.
325 let cap = self.buffer.get().cap;
326
327 // Is there enough capacity to push `reserve_cap` tasks?
328 if cap - len < reserve_cap {
329 // Keep doubling the capacity as much as is needed.
330 let mut new_cap = cap * 2;
331 while new_cap - len < reserve_cap {
332 new_cap *= 2;
333 }
334
335 // Resize the buffer.
336 unsafe {
337 self.resize(new_cap);
338 }
339 }
340 }
341 }
342
343 /// Returns `true` if the queue is empty.
344 ///
345 /// ```
346 /// use crossbeam_deque::Worker;
347 ///
348 /// let w = Worker::new_lifo();
349 ///
350 /// assert!(w.is_empty());
351 /// w.push(1);
352 /// assert!(!w.is_empty());
353 /// ```
354 pub fn is_empty(&self) -> bool {
355 let b = self.inner.back.load(Ordering::Relaxed);
356 let f = self.inner.front.load(Ordering::SeqCst);
357 b.wrapping_sub(f) <= 0
358 }
359
360 /// Returns the number of tasks in the deque.
361 ///
362 /// ```
363 /// use crossbeam_deque::Worker;
364 ///
365 /// let w = Worker::new_lifo();
366 ///
367 /// assert_eq!(w.len(), 0);
368 /// w.push(1);
369 /// assert_eq!(w.len(), 1);
370 /// w.push(1);
371 /// assert_eq!(w.len(), 2);
372 /// ```
373 pub fn len(&self) -> usize {
374 let b = self.inner.back.load(Ordering::Relaxed);
375 let f = self.inner.front.load(Ordering::SeqCst);
376 b.wrapping_sub(f).max(0) as usize
377 }
378
379 /// Pushes a task into the queue.
380 ///
381 /// # Examples
382 ///
383 /// ```
384 /// use crossbeam_deque::Worker;
385 ///
386 /// let w = Worker::new_lifo();
387 /// w.push(1);
388 /// w.push(2);
389 /// ```
390 pub fn push(&self, task: T) {
391 // Load the back index, front index, and buffer.
392 let b = self.inner.back.load(Ordering::Relaxed);
393 let f = self.inner.front.load(Ordering::Acquire);
394 let mut buffer = self.buffer.get();
395
396 // Calculate the length of the queue.
397 let len = b.wrapping_sub(f);
398
399 // Is the queue full?
400 if len >= buffer.cap as isize {
401 // Yes. Grow the underlying buffer.
402 unsafe {
403 self.resize(2 * buffer.cap);
404 }
405 buffer = self.buffer.get();
406 }
407
408 // Write `task` into the slot.
409 unsafe {
410 buffer.write(b, MaybeUninit::new(task));
411 }
412
413 atomic::fence(Ordering::Release);
414
415 // Increment the back index.
416 //
417 // This ordering could be `Relaxed`, but then thread sanitizer would falsely report data
418 // races because it doesn't understand fences.
419 self.inner.back.store(b.wrapping_add(1), Ordering::Release);
420 }
421
422 /// Pops a task from the queue.
423 ///
424 /// # Examples
425 ///
426 /// ```
427 /// use crossbeam_deque::Worker;
428 ///
429 /// let w = Worker::new_fifo();
430 /// w.push(1);
431 /// w.push(2);
432 ///
433 /// assert_eq!(w.pop(), Some(1));
434 /// assert_eq!(w.pop(), Some(2));
435 /// assert_eq!(w.pop(), None);
436 /// ```
437 pub fn pop(&self) -> Option<T> {
438 // Load the back and front index.
439 let b = self.inner.back.load(Ordering::Relaxed);
440 let f = self.inner.front.load(Ordering::Relaxed);
441
442 // Calculate the length of the queue.
443 let len = b.wrapping_sub(f);
444
445 // Is the queue empty?
446 if len <= 0 {
447 return None;
448 }
449
450 match self.flavor {
451 // Pop from the front of the queue.
452 Flavor::Fifo => {
453 // Try incrementing the front index to pop the task.
454 let f = self.inner.front.fetch_add(1, Ordering::SeqCst);
455 let new_f = f.wrapping_add(1);
456
457 if b.wrapping_sub(new_f) < 0 {
458 self.inner.front.store(f, Ordering::Relaxed);
459 return None;
460 }
461
462 unsafe {
463 // Read the popped task.
464 let buffer = self.buffer.get();
465 let task = buffer.read(f).assume_init();
466
467 // Shrink the buffer if `len - 1` is less than one fourth of the capacity.
468 if buffer.cap > MIN_CAP && len <= buffer.cap as isize / 4 {
469 self.resize(buffer.cap / 2);
470 }
471
472 Some(task)
473 }
474 }
475
476 // Pop from the back of the queue.
477 Flavor::Lifo => {
478 // Decrement the back index.
479 let b = b.wrapping_sub(1);
480 self.inner.back.store(b, Ordering::Relaxed);
481
482 atomic::fence(Ordering::SeqCst);
483
484 // Load the front index.
485 let f = self.inner.front.load(Ordering::Relaxed);
486
487 // Compute the length after the back index was decremented.
488 let len = b.wrapping_sub(f);
489
490 if len < 0 {
491 // The queue is empty. Restore the back index to the original task.
492 self.inner.back.store(b.wrapping_add(1), Ordering::Relaxed);
493 None
494 } else {
495 // Read the task to be popped.
496 let buffer = self.buffer.get();
497 let mut task = unsafe { Some(buffer.read(b)) };
498
499 // Are we popping the last task from the queue?
500 if len == 0 {
501 // Try incrementing the front index.
502 if self
503 .inner
504 .front
505 .compare_exchange(
506 f,
507 f.wrapping_add(1),
508 Ordering::SeqCst,
509 Ordering::Relaxed,
510 )
511 .is_err()
512 {
513 // Failed. We didn't pop anything. Reset to `None`.
514 task.take();
515 }
516
517 // Restore the back index to the original task.
518 self.inner.back.store(b.wrapping_add(1), Ordering::Relaxed);
519 } else {
520 // Shrink the buffer if `len` is less than one fourth of the capacity.
521 if buffer.cap > MIN_CAP && len < buffer.cap as isize / 4 {
522 unsafe {
523 self.resize(buffer.cap / 2);
524 }
525 }
526 }
527
528 task.map(|t| unsafe { t.assume_init() })
529 }
530 }
531 }
532 }
533 }
534
535 impl<T> fmt::Debug for Worker<T> {
536 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
537 f.pad("Worker { .. }")
538 }
539 }
540
541 /// A stealer handle of a worker queue.
542 ///
543 /// Stealers can be shared among threads.
544 ///
545 /// Task schedulers typically have a single worker queue per worker thread.
546 ///
547 /// # Examples
548 ///
549 /// ```
550 /// use crossbeam_deque::{Steal, Worker};
551 ///
552 /// let w = Worker::new_lifo();
553 /// w.push(1);
554 /// w.push(2);
555 ///
556 /// let s = w.stealer();
557 /// assert_eq!(s.steal(), Steal::Success(1));
558 /// assert_eq!(s.steal(), Steal::Success(2));
559 /// assert_eq!(s.steal(), Steal::Empty);
560 /// ```
561 pub struct Stealer<T> {
562 /// A reference to the inner representation of the queue.
563 inner: Arc<CachePadded<Inner<T>>>,
564
565 /// The flavor of the queue.
566 flavor: Flavor,
567 }
568
569 unsafe impl<T: Send> Send for Stealer<T> {}
570 unsafe impl<T: Send> Sync for Stealer<T> {}
571
572 impl<T> Stealer<T> {
573 /// Returns `true` if the queue is empty.
574 ///
575 /// ```
576 /// use crossbeam_deque::Worker;
577 ///
578 /// let w = Worker::new_lifo();
579 /// let s = w.stealer();
580 ///
581 /// assert!(s.is_empty());
582 /// w.push(1);
583 /// assert!(!s.is_empty());
584 /// ```
585 pub fn is_empty(&self) -> bool {
586 let f = self.inner.front.load(Ordering::Acquire);
587 atomic::fence(Ordering::SeqCst);
588 let b = self.inner.back.load(Ordering::Acquire);
589 b.wrapping_sub(f) <= 0
590 }
591
592 /// Returns the number of tasks in the deque.
593 ///
594 /// ```
595 /// use crossbeam_deque::Worker;
596 ///
597 /// let w = Worker::new_lifo();
598 /// let s = w.stealer();
599 ///
600 /// assert_eq!(s.len(), 0);
601 /// w.push(1);
602 /// assert_eq!(s.len(), 1);
603 /// w.push(2);
604 /// assert_eq!(s.len(), 2);
605 /// ```
606 pub fn len(&self) -> usize {
607 let f = self.inner.front.load(Ordering::Acquire);
608 atomic::fence(Ordering::SeqCst);
609 let b = self.inner.back.load(Ordering::Acquire);
610 b.wrapping_sub(f).max(0) as usize
611 }
612
613 /// Steals a task from the queue.
614 ///
615 /// # Examples
616 ///
617 /// ```
618 /// use crossbeam_deque::{Steal, Worker};
619 ///
620 /// let w = Worker::new_lifo();
621 /// w.push(1);
622 /// w.push(2);
623 ///
624 /// let s = w.stealer();
625 /// assert_eq!(s.steal(), Steal::Success(1));
626 /// assert_eq!(s.steal(), Steal::Success(2));
627 /// ```
628 pub fn steal(&self) -> Steal<T> {
629 // Load the front index.
630 let f = self.inner.front.load(Ordering::Acquire);
631
632 // A SeqCst fence is needed here.
633 //
634 // If the current thread is already pinned (reentrantly), we must manually issue the
635 // fence. Otherwise, the following pinning will issue the fence anyway, so we don't
636 // have to.
637 if epoch::is_pinned() {
638 atomic::fence(Ordering::SeqCst);
639 }
640
641 let guard = &epoch::pin();
642
643 // Load the back index.
644 let b = self.inner.back.load(Ordering::Acquire);
645
646 // Is the queue empty?
647 if b.wrapping_sub(f) <= 0 {
648 return Steal::Empty;
649 }
650
651 // Load the buffer and read the task at the front.
652 let buffer = self.inner.buffer.load(Ordering::Acquire, guard);
653 let task = unsafe { buffer.deref().read(f) };
654
655 // Try incrementing the front index to steal the task.
656 // If the buffer has been swapped or the increment fails, we retry.
657 if self.inner.buffer.load(Ordering::Acquire, guard) != buffer
658 || self
659 .inner
660 .front
661 .compare_exchange(f, f.wrapping_add(1), Ordering::SeqCst, Ordering::Relaxed)
662 .is_err()
663 {
664 // We didn't steal this task, forget it.
665 return Steal::Retry;
666 }
667
668 // Return the stolen task.
669 Steal::Success(unsafe { task.assume_init() })
670 }
671
672 /// Steals a batch of tasks and pushes them into another worker.
673 ///
674 /// How many tasks exactly will be stolen is not specified. That said, this method will try to
675 /// steal around half of the tasks in the queue, but also not more than some constant limit.
676 ///
677 /// # Examples
678 ///
679 /// ```
680 /// use crossbeam_deque::Worker;
681 ///
682 /// let w1 = Worker::new_fifo();
683 /// w1.push(1);
684 /// w1.push(2);
685 /// w1.push(3);
686 /// w1.push(4);
687 ///
688 /// let s = w1.stealer();
689 /// let w2 = Worker::new_fifo();
690 ///
691 /// let _ = s.steal_batch(&w2);
692 /// assert_eq!(w2.pop(), Some(1));
693 /// assert_eq!(w2.pop(), Some(2));
694 /// ```
695 pub fn steal_batch(&self, dest: &Worker<T>) -> Steal<()> {
696 if Arc::ptr_eq(&self.inner, &dest.inner) {
697 if dest.is_empty() {
698 return Steal::Empty;
699 } else {
700 return Steal::Success(());
701 }
702 }
703
704 // Load the front index.
705 let mut f = self.inner.front.load(Ordering::Acquire);
706
707 // A SeqCst fence is needed here.
708 //
709 // If the current thread is already pinned (reentrantly), we must manually issue the
710 // fence. Otherwise, the following pinning will issue the fence anyway, so we don't
711 // have to.
712 if epoch::is_pinned() {
713 atomic::fence(Ordering::SeqCst);
714 }
715
716 let guard = &epoch::pin();
717
718 // Load the back index.
719 let b = self.inner.back.load(Ordering::Acquire);
720
721 // Is the queue empty?
722 let len = b.wrapping_sub(f);
723 if len <= 0 {
724 return Steal::Empty;
725 }
726
727 // Reserve capacity for the stolen batch.
728 let batch_size = cmp::min((len as usize + 1) / 2, MAX_BATCH);
729 dest.reserve(batch_size);
730 let mut batch_size = batch_size as isize;
731
732 // Get the destination buffer and back index.
733 let dest_buffer = dest.buffer.get();
734 let mut dest_b = dest.inner.back.load(Ordering::Relaxed);
735
736 // Load the buffer.
737 let buffer = self.inner.buffer.load(Ordering::Acquire, guard);
738
739 match self.flavor {
740 // Steal a batch of tasks from the front at once.
741 Flavor::Fifo => {
742 // Copy the batch from the source to the destination buffer.
743 match dest.flavor {
744 Flavor::Fifo => {
745 for i in 0..batch_size {
746 unsafe {
747 let task = buffer.deref().read(f.wrapping_add(i));
748 dest_buffer.write(dest_b.wrapping_add(i), task);
749 }
750 }
751 }
752 Flavor::Lifo => {
753 for i in 0..batch_size {
754 unsafe {
755 let task = buffer.deref().read(f.wrapping_add(i));
756 dest_buffer.write(dest_b.wrapping_add(batch_size - 1 - i), task);
757 }
758 }
759 }
760 }
761
762 // Try incrementing the front index to steal the batch.
763 // If the buffer has been swapped or the increment fails, we retry.
764 if self.inner.buffer.load(Ordering::Acquire, guard) != buffer
765 || self
766 .inner
767 .front
768 .compare_exchange(
769 f,
770 f.wrapping_add(batch_size),
771 Ordering::SeqCst,
772 Ordering::Relaxed,
773 )
774 .is_err()
775 {
776 return Steal::Retry;
777 }
778
779 dest_b = dest_b.wrapping_add(batch_size);
780 }
781
782 // Steal a batch of tasks from the front one by one.
783 Flavor::Lifo => {
784 // This loop may modify the batch_size, which triggers a clippy lint warning.
785 // Use a new variable to avoid the warning, and to make it clear we aren't
786 // modifying the loop exit condition during iteration.
787 let original_batch_size = batch_size;
788
789 for i in 0..original_batch_size {
790 // If this is not the first steal, check whether the queue is empty.
791 if i > 0 {
792 // We've already got the current front index. Now execute the fence to
793 // synchronize with other threads.
794 atomic::fence(Ordering::SeqCst);
795
796 // Load the back index.
797 let b = self.inner.back.load(Ordering::Acquire);
798
799 // Is the queue empty?
800 if b.wrapping_sub(f) <= 0 {
801 batch_size = i;
802 break;
803 }
804 }
805
806 // Read the task at the front.
807 let task = unsafe { buffer.deref().read(f) };
808
809 // Try incrementing the front index to steal the task.
810 // If the buffer has been swapped or the increment fails, we retry.
811 if self.inner.buffer.load(Ordering::Acquire, guard) != buffer
812 || self
813 .inner
814 .front
815 .compare_exchange(
816 f,
817 f.wrapping_add(1),
818 Ordering::SeqCst,
819 Ordering::Relaxed,
820 )
821 .is_err()
822 {
823 // We didn't steal this task, forget it and break from the loop.
824 batch_size = i;
825 break;
826 }
827
828 // Write the stolen task into the destination buffer.
829 unsafe {
830 dest_buffer.write(dest_b, task);
831 }
832
833 // Move the source front index and the destination back index one step forward.
834 f = f.wrapping_add(1);
835 dest_b = dest_b.wrapping_add(1);
836 }
837
838 // If we didn't steal anything, the operation needs to be retried.
839 if batch_size == 0 {
840 return Steal::Retry;
841 }
842
843 // If stealing into a FIFO queue, stolen tasks need to be reversed.
844 if dest.flavor == Flavor::Fifo {
845 for i in 0..batch_size / 2 {
846 unsafe {
847 let i1 = dest_b.wrapping_sub(batch_size - i);
848 let i2 = dest_b.wrapping_sub(i + 1);
849 let t1 = dest_buffer.read(i1);
850 let t2 = dest_buffer.read(i2);
851 dest_buffer.write(i1, t2);
852 dest_buffer.write(i2, t1);
853 }
854 }
855 }
856 }
857 }
858
859 atomic::fence(Ordering::Release);
860
861 // Update the back index in the destination queue.
862 //
863 // This ordering could be `Relaxed`, but then thread sanitizer would falsely report data
864 // races because it doesn't understand fences.
865 dest.inner.back.store(dest_b, Ordering::Release);
866
867 // Return with success.
868 Steal::Success(())
869 }
870
871 /// Steals a batch of tasks, pushes them into another worker, and pops a task from that worker.
872 ///
873 /// How many tasks exactly will be stolen is not specified. That said, this method will try to
874 /// steal around half of the tasks in the queue, but also not more than some constant limit.
875 ///
876 /// # Examples
877 ///
878 /// ```
879 /// use crossbeam_deque::{Steal, Worker};
880 ///
881 /// let w1 = Worker::new_fifo();
882 /// w1.push(1);
883 /// w1.push(2);
884 /// w1.push(3);
885 /// w1.push(4);
886 ///
887 /// let s = w1.stealer();
888 /// let w2 = Worker::new_fifo();
889 ///
890 /// assert_eq!(s.steal_batch_and_pop(&w2), Steal::Success(1));
891 /// assert_eq!(w2.pop(), Some(2));
892 /// ```
893 pub fn steal_batch_and_pop(&self, dest: &Worker<T>) -> Steal<T> {
894 if Arc::ptr_eq(&self.inner, &dest.inner) {
895 match dest.pop() {
896 None => return Steal::Empty,
897 Some(task) => return Steal::Success(task),
898 }
899 }
900
901 // Load the front index.
902 let mut f = self.inner.front.load(Ordering::Acquire);
903
904 // A SeqCst fence is needed here.
905 //
906 // If the current thread is already pinned (reentrantly), we must manually issue the
907 // fence. Otherwise, the following pinning will issue the fence anyway, so we don't
908 // have to.
909 if epoch::is_pinned() {
910 atomic::fence(Ordering::SeqCst);
911 }
912
913 let guard = &epoch::pin();
914
915 // Load the back index.
916 let b = self.inner.back.load(Ordering::Acquire);
917
918 // Is the queue empty?
919 let len = b.wrapping_sub(f);
920 if len <= 0 {
921 return Steal::Empty;
922 }
923
924 // Reserve capacity for the stolen batch.
925 let batch_size = cmp::min((len as usize - 1) / 2, MAX_BATCH - 1);
926 dest.reserve(batch_size);
927 let mut batch_size = batch_size as isize;
928
929 // Get the destination buffer and back index.
930 let dest_buffer = dest.buffer.get();
931 let mut dest_b = dest.inner.back.load(Ordering::Relaxed);
932
933 // Load the buffer
934 let buffer = self.inner.buffer.load(Ordering::Acquire, guard);
935
936 // Read the task at the front.
937 let mut task = unsafe { buffer.deref().read(f) };
938
939 match self.flavor {
940 // Steal a batch of tasks from the front at once.
941 Flavor::Fifo => {
942 // Copy the batch from the source to the destination buffer.
943 match dest.flavor {
944 Flavor::Fifo => {
945 for i in 0..batch_size {
946 unsafe {
947 let task = buffer.deref().read(f.wrapping_add(i + 1));
948 dest_buffer.write(dest_b.wrapping_add(i), task);
949 }
950 }
951 }
952 Flavor::Lifo => {
953 for i in 0..batch_size {
954 unsafe {
955 let task = buffer.deref().read(f.wrapping_add(i + 1));
956 dest_buffer.write(dest_b.wrapping_add(batch_size - 1 - i), task);
957 }
958 }
959 }
960 }
961
962 // Try incrementing the front index to steal the task.
963 // If the buffer has been swapped or the increment fails, we retry.
964 if self.inner.buffer.load(Ordering::Acquire, guard) != buffer
965 || self
966 .inner
967 .front
968 .compare_exchange(
969 f,
970 f.wrapping_add(batch_size + 1),
971 Ordering::SeqCst,
972 Ordering::Relaxed,
973 )
974 .is_err()
975 {
976 // We didn't steal this task, forget it.
977 return Steal::Retry;
978 }
979
980 dest_b = dest_b.wrapping_add(batch_size);
981 }
982
983 // Steal a batch of tasks from the front one by one.
984 Flavor::Lifo => {
985 // Try incrementing the front index to steal the task.
986 if self
987 .inner
988 .front
989 .compare_exchange(f, f.wrapping_add(1), Ordering::SeqCst, Ordering::Relaxed)
990 .is_err()
991 {
992 // We didn't steal this task, forget it.
993 return Steal::Retry;
994 }
995
996 // Move the front index one step forward.
997 f = f.wrapping_add(1);
998
999 // Repeat the same procedure for the batch steals.
1000 //
1001 // This loop may modify the batch_size, which triggers a clippy lint warning.
1002 // Use a new variable to avoid the warning, and to make it clear we aren't
1003 // modifying the loop exit condition during iteration.
1004 let original_batch_size = batch_size;
1005 for i in 0..original_batch_size {
1006 // We've already got the current front index. Now execute the fence to
1007 // synchronize with other threads.
1008 atomic::fence(Ordering::SeqCst);
1009
1010 // Load the back index.
1011 let b = self.inner.back.load(Ordering::Acquire);
1012
1013 // Is the queue empty?
1014 if b.wrapping_sub(f) <= 0 {
1015 batch_size = i;
1016 break;
1017 }
1018
1019 // Read the task at the front.
1020 let tmp = unsafe { buffer.deref().read(f) };
1021
1022 // Try incrementing the front index to steal the task.
1023 // If the buffer has been swapped or the increment fails, we retry.
1024 if self.inner.buffer.load(Ordering::Acquire, guard) != buffer
1025 || self
1026 .inner
1027 .front
1028 .compare_exchange(
1029 f,
1030 f.wrapping_add(1),
1031 Ordering::SeqCst,
1032 Ordering::Relaxed,
1033 )
1034 .is_err()
1035 {
1036 // We didn't steal this task, forget it and break from the loop.
1037 batch_size = i;
1038 break;
1039 }
1040
1041 // Write the previously stolen task into the destination buffer.
1042 unsafe {
1043 dest_buffer.write(dest_b, mem::replace(&mut task, tmp));
1044 }
1045
1046 // Move the source front index and the destination back index one step forward.
1047 f = f.wrapping_add(1);
1048 dest_b = dest_b.wrapping_add(1);
1049 }
1050
1051 // If stealing into a FIFO queue, stolen tasks need to be reversed.
1052 if dest.flavor == Flavor::Fifo {
1053 for i in 0..batch_size / 2 {
1054 unsafe {
1055 let i1 = dest_b.wrapping_sub(batch_size - i);
1056 let i2 = dest_b.wrapping_sub(i + 1);
1057 let t1 = dest_buffer.read(i1);
1058 let t2 = dest_buffer.read(i2);
1059 dest_buffer.write(i1, t2);
1060 dest_buffer.write(i2, t1);
1061 }
1062 }
1063 }
1064 }
1065 }
1066
1067 atomic::fence(Ordering::Release);
1068
1069 // Update the back index in the destination queue.
1070 //
1071 // This ordering could be `Relaxed`, but then thread sanitizer would falsely report data
1072 // races because it doesn't understand fences.
1073 dest.inner.back.store(dest_b, Ordering::Release);
1074
1075 // Return with success.
1076 Steal::Success(unsafe { task.assume_init() })
1077 }
1078 }
1079
1080 impl<T> Clone for Stealer<T> {
1081 fn clone(&self) -> Stealer<T> {
1082 Stealer {
1083 inner: self.inner.clone(),
1084 flavor: self.flavor,
1085 }
1086 }
1087 }
1088
1089 impl<T> fmt::Debug for Stealer<T> {
1090 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1091 f.pad("Stealer { .. }")
1092 }
1093 }
1094
1095 // Bits indicating the state of a slot:
1096 // * If a task has been written into the slot, `WRITE` is set.
1097 // * If a task has been read from the slot, `READ` is set.
1098 // * If the block is being destroyed, `DESTROY` is set.
1099 const WRITE: usize = 1;
1100 const READ: usize = 2;
1101 const DESTROY: usize = 4;
1102
1103 // Each block covers one "lap" of indices.
1104 const LAP: usize = 64;
1105 // The maximum number of values a block can hold.
1106 const BLOCK_CAP: usize = LAP - 1;
1107 // How many lower bits are reserved for metadata.
1108 const SHIFT: usize = 1;
1109 // Indicates that the block is not the last one.
1110 const HAS_NEXT: usize = 1;
1111
1112 /// A slot in a block.
1113 struct Slot<T> {
1114 /// The task.
1115 task: UnsafeCell<MaybeUninit<T>>,
1116
1117 /// The state of the slot.
1118 state: AtomicUsize,
1119 }
1120
1121 impl<T> Slot<T> {
1122 const UNINIT: Self = Self {
1123 task: UnsafeCell::new(MaybeUninit::uninit()),
1124 state: AtomicUsize::new(0),
1125 };
1126
1127 /// Waits until a task is written into the slot.
1128 fn wait_write(&self) {
1129 let backoff = Backoff::new();
1130 while self.state.load(Ordering::Acquire) & WRITE == 0 {
1131 backoff.snooze();
1132 }
1133 }
1134 }
1135
1136 /// A block in a linked list.
1137 ///
1138 /// Each block in the list can hold up to `BLOCK_CAP` values.
1139 struct Block<T> {
1140 /// The next block in the linked list.
1141 next: AtomicPtr<Block<T>>,
1142
1143 /// Slots for values.
1144 slots: [Slot<T>; BLOCK_CAP],
1145 }
1146
1147 impl<T> Block<T> {
1148 /// Creates an empty block that starts at `start_index`.
1149 fn new() -> Block<T> {
1150 Self {
1151 next: AtomicPtr::new(ptr::null_mut()),
1152 slots: [Slot::UNINIT; BLOCK_CAP],
1153 }
1154 }
1155
1156 /// Waits until the next pointer is set.
1157 fn wait_next(&self) -> *mut Block<T> {
1158 let backoff = Backoff::new();
1159 loop {
1160 let next = self.next.load(Ordering::Acquire);
1161 if !next.is_null() {
1162 return next;
1163 }
1164 backoff.snooze();
1165 }
1166 }
1167
1168 /// Sets the `DESTROY` bit in slots starting from `start` and destroys the block.
1169 unsafe fn destroy(this: *mut Block<T>, count: usize) {
1170 // It is not necessary to set the `DESTROY` bit in the last slot because that slot has
1171 // begun destruction of the block.
1172 for i in (0..count).rev() {
1173 let slot = (*this).slots.get_unchecked(i);
1174
1175 // Mark the `DESTROY` bit if a thread is still using the slot.
1176 if slot.state.load(Ordering::Acquire) & READ == 0
1177 && slot.state.fetch_or(DESTROY, Ordering::AcqRel) & READ == 0
1178 {
1179 // If a thread is still using the slot, it will continue destruction of the block.
1180 return;
1181 }
1182 }
1183
1184 // No thread is using the block, now it is safe to destroy it.
1185 drop(Box::from_raw(this));
1186 }
1187 }
1188
1189 /// A position in a queue.
1190 struct Position<T> {
1191 /// The index in the queue.
1192 index: AtomicUsize,
1193
1194 /// The block in the linked list.
1195 block: AtomicPtr<Block<T>>,
1196 }
1197
1198 /// An injector queue.
1199 ///
1200 /// This is a FIFO queue that can be shared among multiple threads. Task schedulers typically have
1201 /// a single injector queue, which is the entry point for new tasks.
1202 ///
1203 /// # Examples
1204 ///
1205 /// ```
1206 /// use crossbeam_deque::{Injector, Steal};
1207 ///
1208 /// let q = Injector::new();
1209 /// q.push(1);
1210 /// q.push(2);
1211 ///
1212 /// assert_eq!(q.steal(), Steal::Success(1));
1213 /// assert_eq!(q.steal(), Steal::Success(2));
1214 /// assert_eq!(q.steal(), Steal::Empty);
1215 /// ```
1216 pub struct Injector<T> {
1217 /// The head of the queue.
1218 head: CachePadded<Position<T>>,
1219
1220 /// The tail of the queue.
1221 tail: CachePadded<Position<T>>,
1222
1223 /// Indicates that dropping a `Injector<T>` may drop values of type `T`.
1224 _marker: PhantomData<T>,
1225 }
1226
1227 unsafe impl<T: Send> Send for Injector<T> {}
1228 unsafe impl<T: Send> Sync for Injector<T> {}
1229
1230 impl<T> Default for Injector<T> {
1231 fn default() -> Self {
1232 let block = Box::into_raw(Box::new(Block::<T>::new()));
1233 Self {
1234 head: CachePadded::new(Position {
1235 block: AtomicPtr::new(block),
1236 index: AtomicUsize::new(0),
1237 }),
1238 tail: CachePadded::new(Position {
1239 block: AtomicPtr::new(block),
1240 index: AtomicUsize::new(0),
1241 }),
1242 _marker: PhantomData,
1243 }
1244 }
1245 }
1246
1247 impl<T> Injector<T> {
1248 /// Creates a new injector queue.
1249 ///
1250 /// # Examples
1251 ///
1252 /// ```
1253 /// use crossbeam_deque::Injector;
1254 ///
1255 /// let q = Injector::<i32>::new();
1256 /// ```
1257 pub fn new() -> Injector<T> {
1258 Self::default()
1259 }
1260
1261 /// Pushes a task into the queue.
1262 ///
1263 /// # Examples
1264 ///
1265 /// ```
1266 /// use crossbeam_deque::Injector;
1267 ///
1268 /// let w = Injector::new();
1269 /// w.push(1);
1270 /// w.push(2);
1271 /// ```
1272 pub fn push(&self, task: T) {
1273 let backoff = Backoff::new();
1274 let mut tail = self.tail.index.load(Ordering::Acquire);
1275 let mut block = self.tail.block.load(Ordering::Acquire);
1276 let mut next_block = None;
1277
1278 loop {
1279 // Calculate the offset of the index into the block.
1280 let offset = (tail >> SHIFT) % LAP;
1281
1282 // If we reached the end of the block, wait until the next one is installed.
1283 if offset == BLOCK_CAP {
1284 backoff.snooze();
1285 tail = self.tail.index.load(Ordering::Acquire);
1286 block = self.tail.block.load(Ordering::Acquire);
1287 continue;
1288 }
1289
1290 // If we're going to have to install the next block, allocate it in advance in order to
1291 // make the wait for other threads as short as possible.
1292 if offset + 1 == BLOCK_CAP && next_block.is_none() {
1293 next_block = Some(Box::new(Block::<T>::new()));
1294 }
1295
1296 let new_tail = tail + (1 << SHIFT);
1297
1298 // Try advancing the tail forward.
1299 match self.tail.index.compare_exchange_weak(
1300 tail,
1301 new_tail,
1302 Ordering::SeqCst,
1303 Ordering::Acquire,
1304 ) {
1305 Ok(_) => unsafe {
1306 // If we've reached the end of the block, install the next one.
1307 if offset + 1 == BLOCK_CAP {
1308 let next_block = Box::into_raw(next_block.unwrap());
1309 let next_index = new_tail.wrapping_add(1 << SHIFT);
1310
1311 self.tail.block.store(next_block, Ordering::Release);
1312 self.tail.index.store(next_index, Ordering::Release);
1313 (*block).next.store(next_block, Ordering::Release);
1314 }
1315
1316 // Write the task into the slot.
1317 let slot = (*block).slots.get_unchecked(offset);
1318 slot.task.get().write(MaybeUninit::new(task));
1319 slot.state.fetch_or(WRITE, Ordering::Release);
1320
1321 return;
1322 },
1323 Err(t) => {
1324 tail = t;
1325 block = self.tail.block.load(Ordering::Acquire);
1326 backoff.spin();
1327 }
1328 }
1329 }
1330 }
1331
1332 /// Steals a task from the queue.
1333 ///
1334 /// # Examples
1335 ///
1336 /// ```
1337 /// use crossbeam_deque::{Injector, Steal};
1338 ///
1339 /// let q = Injector::new();
1340 /// q.push(1);
1341 /// q.push(2);
1342 ///
1343 /// assert_eq!(q.steal(), Steal::Success(1));
1344 /// assert_eq!(q.steal(), Steal::Success(2));
1345 /// assert_eq!(q.steal(), Steal::Empty);
1346 /// ```
1347 pub fn steal(&self) -> Steal<T> {
1348 let mut head;
1349 let mut block;
1350 let mut offset;
1351
1352 let backoff = Backoff::new();
1353 loop {
1354 head = self.head.index.load(Ordering::Acquire);
1355 block = self.head.block.load(Ordering::Acquire);
1356
1357 // Calculate the offset of the index into the block.
1358 offset = (head >> SHIFT) % LAP;
1359
1360 // If we reached the end of the block, wait until the next one is installed.
1361 if offset == BLOCK_CAP {
1362 backoff.snooze();
1363 } else {
1364 break;
1365 }
1366 }
1367
1368 let mut new_head = head + (1 << SHIFT);
1369
1370 if new_head & HAS_NEXT == 0 {
1371 atomic::fence(Ordering::SeqCst);
1372 let tail = self.tail.index.load(Ordering::Relaxed);
1373
1374 // If the tail equals the head, that means the queue is empty.
1375 if head >> SHIFT == tail >> SHIFT {
1376 return Steal::Empty;
1377 }
1378
1379 // If head and tail are not in the same block, set `HAS_NEXT` in head.
1380 if (head >> SHIFT) / LAP != (tail >> SHIFT) / LAP {
1381 new_head |= HAS_NEXT;
1382 }
1383 }
1384
1385 // Try moving the head index forward.
1386 if self
1387 .head
1388 .index
1389 .compare_exchange_weak(head, new_head, Ordering::SeqCst, Ordering::Acquire)
1390 .is_err()
1391 {
1392 return Steal::Retry;
1393 }
1394
1395 unsafe {
1396 // If we've reached the end of the block, move to the next one.
1397 if offset + 1 == BLOCK_CAP {
1398 let next = (*block).wait_next();
1399 let mut next_index = (new_head & !HAS_NEXT).wrapping_add(1 << SHIFT);
1400 if !(*next).next.load(Ordering::Relaxed).is_null() {
1401 next_index |= HAS_NEXT;
1402 }
1403
1404 self.head.block.store(next, Ordering::Release);
1405 self.head.index.store(next_index, Ordering::Release);
1406 }
1407
1408 // Read the task.
1409 let slot = (*block).slots.get_unchecked(offset);
1410 slot.wait_write();
1411 let task = slot.task.get().read().assume_init();
1412
1413 // Destroy the block if we've reached the end, or if another thread wanted to destroy
1414 // but couldn't because we were busy reading from the slot.
1415 if (offset + 1 == BLOCK_CAP)
1416 || (slot.state.fetch_or(READ, Ordering::AcqRel) & DESTROY != 0)
1417 {
1418 Block::destroy(block, offset);
1419 }
1420
1421 Steal::Success(task)
1422 }
1423 }
1424
1425 /// Steals a batch of tasks and pushes them into a worker.
1426 ///
1427 /// How many tasks exactly will be stolen is not specified. That said, this method will try to
1428 /// steal around half of the tasks in the queue, but also not more than some constant limit.
1429 ///
1430 /// # Examples
1431 ///
1432 /// ```
1433 /// use crossbeam_deque::{Injector, Worker};
1434 ///
1435 /// let q = Injector::new();
1436 /// q.push(1);
1437 /// q.push(2);
1438 /// q.push(3);
1439 /// q.push(4);
1440 ///
1441 /// let w = Worker::new_fifo();
1442 /// let _ = q.steal_batch(&w);
1443 /// assert_eq!(w.pop(), Some(1));
1444 /// assert_eq!(w.pop(), Some(2));
1445 /// ```
1446 pub fn steal_batch(&self, dest: &Worker<T>) -> Steal<()> {
1447 let mut head;
1448 let mut block;
1449 let mut offset;
1450
1451 let backoff = Backoff::new();
1452 loop {
1453 head = self.head.index.load(Ordering::Acquire);
1454 block = self.head.block.load(Ordering::Acquire);
1455
1456 // Calculate the offset of the index into the block.
1457 offset = (head >> SHIFT) % LAP;
1458
1459 // If we reached the end of the block, wait until the next one is installed.
1460 if offset == BLOCK_CAP {
1461 backoff.snooze();
1462 } else {
1463 break;
1464 }
1465 }
1466
1467 let mut new_head = head;
1468 let advance;
1469
1470 if new_head & HAS_NEXT == 0 {
1471 atomic::fence(Ordering::SeqCst);
1472 let tail = self.tail.index.load(Ordering::Relaxed);
1473
1474 // If the tail equals the head, that means the queue is empty.
1475 if head >> SHIFT == tail >> SHIFT {
1476 return Steal::Empty;
1477 }
1478
1479 // If head and tail are not in the same block, set `HAS_NEXT` in head. Also, calculate
1480 // the right batch size to steal.
1481 if (head >> SHIFT) / LAP != (tail >> SHIFT) / LAP {
1482 new_head |= HAS_NEXT;
1483 // We can steal all tasks till the end of the block.
1484 advance = (BLOCK_CAP - offset).min(MAX_BATCH);
1485 } else {
1486 let len = (tail - head) >> SHIFT;
1487 // Steal half of the available tasks.
1488 advance = ((len + 1) / 2).min(MAX_BATCH);
1489 }
1490 } else {
1491 // We can steal all tasks till the end of the block.
1492 advance = (BLOCK_CAP - offset).min(MAX_BATCH);
1493 }
1494
1495 new_head += advance << SHIFT;
1496 let new_offset = offset + advance;
1497
1498 // Try moving the head index forward.
1499 if self
1500 .head
1501 .index
1502 .compare_exchange_weak(head, new_head, Ordering::SeqCst, Ordering::Acquire)
1503 .is_err()
1504 {
1505 return Steal::Retry;
1506 }
1507
1508 // Reserve capacity for the stolen batch.
1509 let batch_size = new_offset - offset;
1510 dest.reserve(batch_size);
1511
1512 // Get the destination buffer and back index.
1513 let dest_buffer = dest.buffer.get();
1514 let dest_b = dest.inner.back.load(Ordering::Relaxed);
1515
1516 unsafe {
1517 // If we've reached the end of the block, move to the next one.
1518 if new_offset == BLOCK_CAP {
1519 let next = (*block).wait_next();
1520 let mut next_index = (new_head & !HAS_NEXT).wrapping_add(1 << SHIFT);
1521 if !(*next).next.load(Ordering::Relaxed).is_null() {
1522 next_index |= HAS_NEXT;
1523 }
1524
1525 self.head.block.store(next, Ordering::Release);
1526 self.head.index.store(next_index, Ordering::Release);
1527 }
1528
1529 // Copy values from the injector into the destination queue.
1530 match dest.flavor {
1531 Flavor::Fifo => {
1532 for i in 0..batch_size {
1533 // Read the task.
1534 let slot = (*block).slots.get_unchecked(offset + i);
1535 slot.wait_write();
1536 let task = slot.task.get().read();
1537
1538 // Write it into the destination queue.
1539 dest_buffer.write(dest_b.wrapping_add(i as isize), task);
1540 }
1541 }
1542
1543 Flavor::Lifo => {
1544 for i in 0..batch_size {
1545 // Read the task.
1546 let slot = (*block).slots.get_unchecked(offset + i);
1547 slot.wait_write();
1548 let task = slot.task.get().read();
1549
1550 // Write it into the destination queue.
1551 dest_buffer.write(dest_b.wrapping_add((batch_size - 1 - i) as isize), task);
1552 }
1553 }
1554 }
1555
1556 atomic::fence(Ordering::Release);
1557
1558 // Update the back index in the destination queue.
1559 //
1560 // This ordering could be `Relaxed`, but then thread sanitizer would falsely report
1561 // data races because it doesn't understand fences.
1562 dest.inner
1563 .back
1564 .store(dest_b.wrapping_add(batch_size as isize), Ordering::Release);
1565
1566 // Destroy the block if we've reached the end, or if another thread wanted to destroy
1567 // but couldn't because we were busy reading from the slot.
1568 if new_offset == BLOCK_CAP {
1569 Block::destroy(block, offset);
1570 } else {
1571 for i in offset..new_offset {
1572 let slot = (*block).slots.get_unchecked(i);
1573
1574 if slot.state.fetch_or(READ, Ordering::AcqRel) & DESTROY != 0 {
1575 Block::destroy(block, offset);
1576 break;
1577 }
1578 }
1579 }
1580
1581 Steal::Success(())
1582 }
1583 }
1584
1585 /// Steals a batch of tasks, pushes them into a worker, and pops a task from that worker.
1586 ///
1587 /// How many tasks exactly will be stolen is not specified. That said, this method will try to
1588 /// steal around half of the tasks in the queue, but also not more than some constant limit.
1589 ///
1590 /// # Examples
1591 ///
1592 /// ```
1593 /// use crossbeam_deque::{Injector, Steal, Worker};
1594 ///
1595 /// let q = Injector::new();
1596 /// q.push(1);
1597 /// q.push(2);
1598 /// q.push(3);
1599 /// q.push(4);
1600 ///
1601 /// let w = Worker::new_fifo();
1602 /// assert_eq!(q.steal_batch_and_pop(&w), Steal::Success(1));
1603 /// assert_eq!(w.pop(), Some(2));
1604 /// ```
1605 pub fn steal_batch_and_pop(&self, dest: &Worker<T>) -> Steal<T> {
1606 let mut head;
1607 let mut block;
1608 let mut offset;
1609
1610 let backoff = Backoff::new();
1611 loop {
1612 head = self.head.index.load(Ordering::Acquire);
1613 block = self.head.block.load(Ordering::Acquire);
1614
1615 // Calculate the offset of the index into the block.
1616 offset = (head >> SHIFT) % LAP;
1617
1618 // If we reached the end of the block, wait until the next one is installed.
1619 if offset == BLOCK_CAP {
1620 backoff.snooze();
1621 } else {
1622 break;
1623 }
1624 }
1625
1626 let mut new_head = head;
1627 let advance;
1628
1629 if new_head & HAS_NEXT == 0 {
1630 atomic::fence(Ordering::SeqCst);
1631 let tail = self.tail.index.load(Ordering::Relaxed);
1632
1633 // If the tail equals the head, that means the queue is empty.
1634 if head >> SHIFT == tail >> SHIFT {
1635 return Steal::Empty;
1636 }
1637
1638 // If head and tail are not in the same block, set `HAS_NEXT` in head.
1639 if (head >> SHIFT) / LAP != (tail >> SHIFT) / LAP {
1640 new_head |= HAS_NEXT;
1641 // We can steal all tasks till the end of the block.
1642 advance = (BLOCK_CAP - offset).min(MAX_BATCH + 1);
1643 } else {
1644 let len = (tail - head) >> SHIFT;
1645 // Steal half of the available tasks.
1646 advance = ((len + 1) / 2).min(MAX_BATCH + 1);
1647 }
1648 } else {
1649 // We can steal all tasks till the end of the block.
1650 advance = (BLOCK_CAP - offset).min(MAX_BATCH + 1);
1651 }
1652
1653 new_head += advance << SHIFT;
1654 let new_offset = offset + advance;
1655
1656 // Try moving the head index forward.
1657 if self
1658 .head
1659 .index
1660 .compare_exchange_weak(head, new_head, Ordering::SeqCst, Ordering::Acquire)
1661 .is_err()
1662 {
1663 return Steal::Retry;
1664 }
1665
1666 // Reserve capacity for the stolen batch.
1667 let batch_size = new_offset - offset - 1;
1668 dest.reserve(batch_size);
1669
1670 // Get the destination buffer and back index.
1671 let dest_buffer = dest.buffer.get();
1672 let dest_b = dest.inner.back.load(Ordering::Relaxed);
1673
1674 unsafe {
1675 // If we've reached the end of the block, move to the next one.
1676 if new_offset == BLOCK_CAP {
1677 let next = (*block).wait_next();
1678 let mut next_index = (new_head & !HAS_NEXT).wrapping_add(1 << SHIFT);
1679 if !(*next).next.load(Ordering::Relaxed).is_null() {
1680 next_index |= HAS_NEXT;
1681 }
1682
1683 self.head.block.store(next, Ordering::Release);
1684 self.head.index.store(next_index, Ordering::Release);
1685 }
1686
1687 // Read the task.
1688 let slot = (*block).slots.get_unchecked(offset);
1689 slot.wait_write();
1690 let task = slot.task.get().read();
1691
1692 match dest.flavor {
1693 Flavor::Fifo => {
1694 // Copy values from the injector into the destination queue.
1695 for i in 0..batch_size {
1696 // Read the task.
1697 let slot = (*block).slots.get_unchecked(offset + i + 1);
1698 slot.wait_write();
1699 let task = slot.task.get().read();
1700
1701 // Write it into the destination queue.
1702 dest_buffer.write(dest_b.wrapping_add(i as isize), task);
1703 }
1704 }
1705
1706 Flavor::Lifo => {
1707 // Copy values from the injector into the destination queue.
1708 for i in 0..batch_size {
1709 // Read the task.
1710 let slot = (*block).slots.get_unchecked(offset + i + 1);
1711 slot.wait_write();
1712 let task = slot.task.get().read();
1713
1714 // Write it into the destination queue.
1715 dest_buffer.write(dest_b.wrapping_add((batch_size - 1 - i) as isize), task);
1716 }
1717 }
1718 }
1719
1720 atomic::fence(Ordering::Release);
1721
1722 // Update the back index in the destination queue.
1723 //
1724 // This ordering could be `Relaxed`, but then thread sanitizer would falsely report
1725 // data races because it doesn't understand fences.
1726 dest.inner
1727 .back
1728 .store(dest_b.wrapping_add(batch_size as isize), Ordering::Release);
1729
1730 // Destroy the block if we've reached the end, or if another thread wanted to destroy
1731 // but couldn't because we were busy reading from the slot.
1732 if new_offset == BLOCK_CAP {
1733 Block::destroy(block, offset);
1734 } else {
1735 for i in offset..new_offset {
1736 let slot = (*block).slots.get_unchecked(i);
1737
1738 if slot.state.fetch_or(READ, Ordering::AcqRel) & DESTROY != 0 {
1739 Block::destroy(block, offset);
1740 break;
1741 }
1742 }
1743 }
1744
1745 Steal::Success(task.assume_init())
1746 }
1747 }
1748
1749 /// Returns `true` if the queue is empty.
1750 ///
1751 /// # Examples
1752 ///
1753 /// ```
1754 /// use crossbeam_deque::Injector;
1755 ///
1756 /// let q = Injector::new();
1757 ///
1758 /// assert!(q.is_empty());
1759 /// q.push(1);
1760 /// assert!(!q.is_empty());
1761 /// ```
1762 pub fn is_empty(&self) -> bool {
1763 let head = self.head.index.load(Ordering::SeqCst);
1764 let tail = self.tail.index.load(Ordering::SeqCst);
1765 head >> SHIFT == tail >> SHIFT
1766 }
1767
1768 /// Returns the number of tasks in the queue.
1769 ///
1770 /// # Examples
1771 ///
1772 /// ```
1773 /// use crossbeam_deque::Injector;
1774 ///
1775 /// let q = Injector::new();
1776 ///
1777 /// assert_eq!(q.len(), 0);
1778 /// q.push(1);
1779 /// assert_eq!(q.len(), 1);
1780 /// q.push(1);
1781 /// assert_eq!(q.len(), 2);
1782 /// ```
1783 pub fn len(&self) -> usize {
1784 loop {
1785 // Load the tail index, then load the head index.
1786 let mut tail = self.tail.index.load(Ordering::SeqCst);
1787 let mut head = self.head.index.load(Ordering::SeqCst);
1788
1789 // If the tail index didn't change, we've got consistent indices to work with.
1790 if self.tail.index.load(Ordering::SeqCst) == tail {
1791 // Erase the lower bits.
1792 tail &= !((1 << SHIFT) - 1);
1793 head &= !((1 << SHIFT) - 1);
1794
1795 // Fix up indices if they fall onto block ends.
1796 if (tail >> SHIFT) & (LAP - 1) == LAP - 1 {
1797 tail = tail.wrapping_add(1 << SHIFT);
1798 }
1799 if (head >> SHIFT) & (LAP - 1) == LAP - 1 {
1800 head = head.wrapping_add(1 << SHIFT);
1801 }
1802
1803 // Rotate indices so that head falls into the first block.
1804 let lap = (head >> SHIFT) / LAP;
1805 tail = tail.wrapping_sub((lap * LAP) << SHIFT);
1806 head = head.wrapping_sub((lap * LAP) << SHIFT);
1807
1808 // Remove the lower bits.
1809 tail >>= SHIFT;
1810 head >>= SHIFT;
1811
1812 // Return the difference minus the number of blocks between tail and head.
1813 return tail - head - tail / LAP;
1814 }
1815 }
1816 }
1817 }
1818
1819 impl<T> Drop for Injector<T> {
1820 fn drop(&mut self) {
1821 let mut head = *self.head.index.get_mut();
1822 let mut tail = *self.tail.index.get_mut();
1823 let mut block = *self.head.block.get_mut();
1824
1825 // Erase the lower bits.
1826 head &= !((1 << SHIFT) - 1);
1827 tail &= !((1 << SHIFT) - 1);
1828
1829 unsafe {
1830 // Drop all values between `head` and `tail` and deallocate the heap-allocated blocks.
1831 while head != tail {
1832 let offset = (head >> SHIFT) % LAP;
1833
1834 if offset < BLOCK_CAP {
1835 // Drop the task in the slot.
1836 let slot = (*block).slots.get_unchecked(offset);
1837 let p = &mut *slot.task.get();
1838 p.as_mut_ptr().drop_in_place();
1839 } else {
1840 // Deallocate the block and move to the next one.
1841 let next = *(*block).next.get_mut();
1842 drop(Box::from_raw(block));
1843 block = next;
1844 }
1845
1846 head = head.wrapping_add(1 << SHIFT);
1847 }
1848
1849 // Deallocate the last remaining block.
1850 drop(Box::from_raw(block));
1851 }
1852 }
1853 }
1854
1855 impl<T> fmt::Debug for Injector<T> {
1856 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1857 f.pad("Worker { .. }")
1858 }
1859 }
1860
1861 /// Possible outcomes of a steal operation.
1862 ///
1863 /// # Examples
1864 ///
1865 /// There are lots of ways to chain results of steal operations together:
1866 ///
1867 /// ```
1868 /// use crossbeam_deque::Steal::{self, Empty, Retry, Success};
1869 ///
1870 /// let collect = |v: Vec<Steal<i32>>| v.into_iter().collect::<Steal<i32>>();
1871 ///
1872 /// assert_eq!(collect(vec![Empty, Empty, Empty]), Empty);
1873 /// assert_eq!(collect(vec![Empty, Retry, Empty]), Retry);
1874 /// assert_eq!(collect(vec![Retry, Success(1), Empty]), Success(1));
1875 ///
1876 /// assert_eq!(collect(vec![Empty, Empty]).or_else(|| Retry), Retry);
1877 /// assert_eq!(collect(vec![Retry, Empty]).or_else(|| Success(1)), Success(1));
1878 /// ```
1879 #[must_use]
1880 #[derive(PartialEq, Eq, Copy, Clone)]
1881 pub enum Steal<T> {
1882 /// The queue was empty at the time of stealing.
1883 Empty,
1884
1885 /// At least one task was successfully stolen.
1886 Success(T),
1887
1888 /// The steal operation needs to be retried.
1889 Retry,
1890 }
1891
1892 impl<T> Steal<T> {
1893 /// Returns `true` if the queue was empty at the time of stealing.
1894 ///
1895 /// # Examples
1896 ///
1897 /// ```
1898 /// use crossbeam_deque::Steal::{Empty, Retry, Success};
1899 ///
1900 /// assert!(!Success(7).is_empty());
1901 /// assert!(!Retry::<i32>.is_empty());
1902 ///
1903 /// assert!(Empty::<i32>.is_empty());
1904 /// ```
1905 pub fn is_empty(&self) -> bool {
1906 match self {
1907 Steal::Empty => true,
1908 _ => false,
1909 }
1910 }
1911
1912 /// Returns `true` if at least one task was stolen.
1913 ///
1914 /// # Examples
1915 ///
1916 /// ```
1917 /// use crossbeam_deque::Steal::{Empty, Retry, Success};
1918 ///
1919 /// assert!(!Empty::<i32>.is_success());
1920 /// assert!(!Retry::<i32>.is_success());
1921 ///
1922 /// assert!(Success(7).is_success());
1923 /// ```
1924 pub fn is_success(&self) -> bool {
1925 match self {
1926 Steal::Success(_) => true,
1927 _ => false,
1928 }
1929 }
1930
1931 /// Returns `true` if the steal operation needs to be retried.
1932 ///
1933 /// # Examples
1934 ///
1935 /// ```
1936 /// use crossbeam_deque::Steal::{Empty, Retry, Success};
1937 ///
1938 /// assert!(!Empty::<i32>.is_retry());
1939 /// assert!(!Success(7).is_retry());
1940 ///
1941 /// assert!(Retry::<i32>.is_retry());
1942 /// ```
1943 pub fn is_retry(&self) -> bool {
1944 match self {
1945 Steal::Retry => true,
1946 _ => false,
1947 }
1948 }
1949
1950 /// Returns the result of the operation, if successful.
1951 ///
1952 /// # Examples
1953 ///
1954 /// ```
1955 /// use crossbeam_deque::Steal::{Empty, Retry, Success};
1956 ///
1957 /// assert_eq!(Empty::<i32>.success(), None);
1958 /// assert_eq!(Retry::<i32>.success(), None);
1959 ///
1960 /// assert_eq!(Success(7).success(), Some(7));
1961 /// ```
1962 pub fn success(self) -> Option<T> {
1963 match self {
1964 Steal::Success(res) => Some(res),
1965 _ => None,
1966 }
1967 }
1968
1969 /// If no task was stolen, attempts another steal operation.
1970 ///
1971 /// Returns this steal result if it is `Success`. Otherwise, closure `f` is invoked and then:
1972 ///
1973 /// * If the second steal resulted in `Success`, it is returned.
1974 /// * If both steals were unsuccessful but any resulted in `Retry`, then `Retry` is returned.
1975 /// * If both resulted in `None`, then `None` is returned.
1976 ///
1977 /// # Examples
1978 ///
1979 /// ```
1980 /// use crossbeam_deque::Steal::{Empty, Retry, Success};
1981 ///
1982 /// assert_eq!(Success(1).or_else(|| Success(2)), Success(1));
1983 /// assert_eq!(Retry.or_else(|| Success(2)), Success(2));
1984 ///
1985 /// assert_eq!(Retry.or_else(|| Empty), Retry::<i32>);
1986 /// assert_eq!(Empty.or_else(|| Retry), Retry::<i32>);
1987 ///
1988 /// assert_eq!(Empty.or_else(|| Empty), Empty::<i32>);
1989 /// ```
1990 pub fn or_else<F>(self, f: F) -> Steal<T>
1991 where
1992 F: FnOnce() -> Steal<T>,
1993 {
1994 match self {
1995 Steal::Empty => f(),
1996 Steal::Success(_) => self,
1997 Steal::Retry => {
1998 if let Steal::Success(res) = f() {
1999 Steal::Success(res)
2000 } else {
2001 Steal::Retry
2002 }
2003 }
2004 }
2005 }
2006 }
2007
2008 impl<T> fmt::Debug for Steal<T> {
2009 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2010 match self {
2011 Steal::Empty => f.pad("Empty"),
2012 Steal::Success(_) => f.pad("Success(..)"),
2013 Steal::Retry => f.pad("Retry"),
2014 }
2015 }
2016 }
2017
2018 impl<T> FromIterator<Steal<T>> for Steal<T> {
2019 /// Consumes items until a `Success` is found and returns it.
2020 ///
2021 /// If no `Success` was found, but there was at least one `Retry`, then returns `Retry`.
2022 /// Otherwise, `Empty` is returned.
2023 fn from_iter<I>(iter: I) -> Steal<T>
2024 where
2025 I: IntoIterator<Item = Steal<T>>,
2026 {
2027 let mut retry = false;
2028 for s in iter {
2029 match &s {
2030 Steal::Empty => {}
2031 Steal::Success(_) => return s,
2032 Steal::Retry => retry = true,
2033 }
2034 }
2035
2036 if retry {
2037 Steal::Retry
2038 } else {
2039 Steal::Empty
2040 }
2041 }
2042 }