-
Notifications
You must be signed in to change notification settings - Fork 474
/
deque.rs
2044 lines (1793 loc) · 65.7 KB
/
deque.rs
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::cell::{Cell, UnsafeCell};
use std::cmp;
use std::fmt;
use std::iter::FromIterator;
use std::marker::PhantomData;
use std::mem::{self, MaybeUninit};
use std::ptr;
use std::sync::atomic::{self, AtomicIsize, AtomicPtr, AtomicUsize, Ordering};
use std::sync::Arc;
use crate::epoch::{self, Atomic, Owned};
use crate::utils::{Backoff, CachePadded};
// Minimum buffer capacity.
const MIN_CAP: usize = 64;
// Maximum number of tasks that can be stolen in `steal_batch()` and `steal_batch_and_pop()`.
const MAX_BATCH: usize = 32;
// 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`.
///
/// This method might be concurrently called with another `read` at the same index, which is
/// technically speaking a data race and therefore UB. We should use an atomic store here, but
/// that would be more expensive and difficult to implement generically for all types `T`.
/// Hence, as a hack, we use a volatile write instead.
unsafe fn write(&self, index: isize, task: T) {
ptr::write_volatile(self.at(index), task)
}
/// Reads a task from the specified `index`.
///
/// This method might be concurrently called with another `write` at the same index, which is
/// technically speaking a data race and therefore UB. We should use an atomic load here, but
/// that would be more expensive and difficult to implement generically for all types `T`.
/// Hence, as a hack, we use a volatile write instead.
unsafe fn read(&self, index: isize) -> T {
ptr::read_volatile(self.at(index))
}
}
impl<T> Clone for Buffer<T> {
fn clone(&self) -> Buffer<T> {
Buffer {
ptr: self.ptr,
cap: self.cap,
}
}
}
impl<T> Copy for Buffer<T> {}
/// Internal queue data shared between the worker and stealers.
///
/// The implementation is based on the following work:
///
/// 1. [Chase and Lev. Dynamic circular work-stealing deque. SPAA 2005.][chase-lev]
/// 2. [Le, Pop, Cohen, and Nardelli. Correct and efficient work-stealing for weak memory models.
/// PPoPP 2013.][weak-mem]
/// 3. [Norris and Demsky. CDSchecker: checking concurrent data structures written with C/C++
/// atomics. OOPSLA 2013.][checker]
///
/// [chase-lev]: https://dl.acm.org/citation.cfm?id=1073974
/// [weak-mem]: https://dl.acm.org/citation.cfm?id=2442524
/// [checker]: https://dl.acm.org/citation.cfm?id=2509514
struct Inner<T> {
/// The front index.
front: AtomicIsize,
/// The back index.
back: AtomicIsize,
/// The underlying buffer.
buffer: CachePadded<Atomic<Buffer<T>>>,
}
impl<T> Drop for Inner<T> {
fn drop(&mut self) {
// Load the back index, front index, and buffer.
let b = self.back.load(Ordering::Relaxed);
let f = self.front.load(Ordering::Relaxed);
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.
let mut i = f;
while i != b {
buffer.deref().at(i).drop_in_place();
i = i.wrapping_add(1);
}
// Free the memory allocated by the buffer.
buffer.into_owned().into_box().dealloc();
}
}
}
/// Worker queue flavor: FIFO or LIFO.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Flavor {
/// The first-in first-out flavor.
Fifo,
/// The last-in first-out flavor.
Lifo,
}
/// A worker queue.
///
/// This is a FIFO or LIFO queue that is owned by a single thread, but other threads may steal
/// tasks from it. Task schedulers typically create a single worker queue per thread.
///
/// # Examples
///
/// A FIFO worker:
///
/// ```
/// use crossbeam_deque::{Steal, Worker};
///
/// let w = Worker::new_fifo();
/// let s = w.stealer();
///
/// w.push(1);
/// w.push(2);
/// w.push(3);
///
/// assert_eq!(s.steal(), Steal::Success(1));
/// assert_eq!(w.pop(), Some(2));
/// assert_eq!(w.pop(), Some(3));
/// ```
///
/// A LIFO worker:
///
/// ```
/// use crossbeam_deque::{Steal, Worker};
///
/// let w = Worker::new_lifo();
/// let s = w.stealer();
///
/// w.push(1);
/// w.push(2);
/// w.push(3);
///
/// assert_eq!(s.steal(), Steal::Success(1));
/// assert_eq!(w.pop(), Some(3));
/// assert_eq!(w.pop(), Some(2));
/// ```
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>>,
/// The flavor of the queue.
flavor: Flavor,
/// Indicates that the worker cannot be shared among threads.
_marker: PhantomData<*mut ()>, // !Send + !Sync
}
unsafe impl<T: Send> Send for Worker<T> {}
impl<T> Worker<T> {
/// Creates a FIFO worker queue.
///
/// Tasks are pushed and popped from opposite ends.
///
/// # Examples
///
/// ```
/// use crossbeam_deque::Worker;
///
/// let w = Worker::<i32>::new_fifo();
/// ```
pub fn new_fifo() -> Worker<T> {
let buffer = Buffer::alloc(MIN_CAP);
let inner = Arc::new(CachePadded::new(Inner {
front: AtomicIsize::new(0),
back: AtomicIsize::new(0),
buffer: CachePadded::new(Atomic::new(buffer)),
}));
Worker {
inner,
buffer: Cell::new(buffer),
flavor: Flavor::Fifo,
_marker: PhantomData,
}
}
/// Creates a LIFO worker queue.
///
/// Tasks are pushed and popped from the same end.
///
/// # Examples
///
/// ```
/// use crossbeam_deque::Worker;
///
/// let w = Worker::<i32>::new_lifo();
/// ```
pub fn new_lifo() -> Worker<T> {
let buffer = Buffer::alloc(MIN_CAP);
let inner = Arc::new(CachePadded::new(Inner {
front: AtomicIsize::new(0),
back: AtomicIsize::new(0),
buffer: CachePadded::new(Atomic::new(buffer)),
}));
Worker {
inner,
buffer: Cell::new(buffer),
flavor: Flavor::Lifo,
_marker: PhantomData,
}
}
/// Creates a stealer for this queue.
///
/// The returned stealer can be shared among threads and cloned.
///
/// # Examples
///
/// ```
/// use crossbeam_deque::Worker;
///
/// let w = Worker::<i32>::new_lifo();
/// let s = w.stealer();
/// ```
pub fn stealer(&self) -> Stealer<T> {
Stealer {
inner: self.inner.clone(),
flavor: self.flavor,
}
}
/// Resizes the internal buffer to the new capacity of `new_cap`.
#[cold]
unsafe fn resize(&self, new_cap: usize) {
// Load the back index, front index, and buffer.
let b = self.inner.back.load(Ordering::Relaxed);
let f = self.inner.front.load(Ordering::Relaxed);
let buffer = self.buffer.get();
// Allocate a new buffer and copy data from the old buffer to the new one.
let new = Buffer::alloc(new_cap);
let mut i = f;
while i != b {
ptr::copy_nonoverlapping(buffer.at(i), new.at(i), 1);
i = i.wrapping_add(1);
}
let guard = &epoch::pin();
// Replace the old buffer with the new one.
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();
}
}
/// Reserves enough capacity so that `reserve_cap` tasks can be pushed without growing the
/// buffer.
fn reserve(&self, reserve_cap: usize) {
if reserve_cap > 0 {
// Compute the current length.
let b = self.inner.back.load(Ordering::Relaxed);
let f = self.inner.front.load(Ordering::SeqCst);
let len = b.wrapping_sub(f) as usize;
// The current capacity.
let cap = self.buffer.get().cap;
// Is there enough capacity to push `reserve_cap` tasks?
if cap - len < reserve_cap {
// Keep doubling the capacity as much as is needed.
let mut new_cap = cap * 2;
while new_cap - len < reserve_cap {
new_cap *= 2;
}
// Resize the buffer.
unsafe {
self.resize(new_cap);
}
}
}
}
/// Returns `true` if the queue is empty.
///
/// ```
/// use crossbeam_deque::Worker;
///
/// let w = Worker::new_lifo();
///
/// assert!(w.is_empty());
/// w.push(1);
/// assert!(!w.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
let b = self.inner.back.load(Ordering::Relaxed);
let f = self.inner.front.load(Ordering::SeqCst);
b.wrapping_sub(f) <= 0
}
/// Returns the number of tasks in the deque.
///
/// ```
/// use crossbeam_deque::Worker;
///
/// let w = Worker::new_lifo();
///
/// assert_eq!(w.len(), 0);
/// w.push(1);
/// assert_eq!(w.len(), 1);
/// w.push(1);
/// assert_eq!(w.len(), 2);
/// ```
pub fn len(&self) -> usize {
let b = self.inner.back.load(Ordering::Relaxed);
let f = self.inner.front.load(Ordering::SeqCst);
b.wrapping_sub(f).max(0) as usize
}
/// Pushes a task into the queue.
///
/// # Examples
///
/// ```
/// use crossbeam_deque::Worker;
///
/// let w = Worker::new_lifo();
/// w.push(1);
/// w.push(2);
/// ```
pub fn push(&self, task: T) {
// Load the back index, front index, and buffer.
let b = self.inner.back.load(Ordering::Relaxed);
let f = self.inner.front.load(Ordering::Acquire);
let mut buffer = self.buffer.get();
// Calculate the length of the queue.
let len = b.wrapping_sub(f);
// Is the queue full?
if len >= 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(b, task);
}
atomic::fence(Ordering::Release);
// Increment the back index.
//
// This ordering could be `Relaxed`, but then thread sanitizer would falsely report data
// races because it doesn't understand fences.
self.inner.back.store(b.wrapping_add(1), Ordering::Release);
}
/// Pops a task from the queue.
///
/// # Examples
///
/// ```
/// use crossbeam_deque::Worker;
///
/// let w = Worker::new_fifo();
/// w.push(1);
/// w.push(2);
///
/// assert_eq!(w.pop(), Some(1));
/// assert_eq!(w.pop(), Some(2));
/// assert_eq!(w.pop(), None);
/// ```
pub fn pop(&self) -> Option<T> {
// Load the back and front index.
let b = self.inner.back.load(Ordering::Relaxed);
let f = self.inner.front.load(Ordering::Relaxed);
// Calculate the length of the queue.
let len = b.wrapping_sub(f);
// Is the queue empty?
if len <= 0 {
return None;
}
match self.flavor {
// Pop from the front of the queue.
Flavor::Fifo => {
// Try incrementing the front index to pop the task.
let f = self.inner.front.fetch_add(1, Ordering::SeqCst);
let new_f = f.wrapping_add(1);
if b.wrapping_sub(new_f) < 0 {
self.inner.front.store(f, Ordering::Relaxed);
return None;
}
unsafe {
// Read the popped task.
let buffer = self.buffer.get();
let task = buffer.read(f);
// Shrink the buffer if `len - 1` is less than one fourth of the capacity.
if buffer.cap > MIN_CAP && len <= buffer.cap as isize / 4 {
self.resize(buffer.cap / 2);
}
Some(task)
}
}
// Pop from the back of the queue.
Flavor::Lifo => {
// Decrement the back index.
let b = b.wrapping_sub(1);
self.inner.back.store(b, Ordering::Relaxed);
atomic::fence(Ordering::SeqCst);
// Load the front index.
let f = self.inner.front.load(Ordering::Relaxed);
// Compute the length after the back index was decremented.
let len = b.wrapping_sub(f);
if len < 0 {
// The queue is empty. Restore the back index to the original task.
self.inner.back.store(b.wrapping_add(1), Ordering::Relaxed);
None
} else {
// Read the task to be popped.
let buffer = self.buffer.get();
let mut task = unsafe { Some(buffer.read(b)) };
// Are we popping the last task from the queue?
if len == 0 {
// Try incrementing the front index.
if self
.inner
.front
.compare_exchange(
f,
f.wrapping_add(1),
Ordering::SeqCst,
Ordering::Relaxed,
)
.is_err()
{
// Failed. We didn't pop anything.
mem::forget(task.take());
}
// Restore the back index to the original task.
self.inner.back.store(b.wrapping_add(1), Ordering::Relaxed);
} else {
// Shrink the buffer if `len` is less than one fourth of the capacity.
if buffer.cap > MIN_CAP && len < buffer.cap as isize / 4 {
unsafe {
self.resize(buffer.cap / 2);
}
}
}
task
}
}
}
}
}
impl<T> fmt::Debug for Worker<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("Worker { .. }")
}
}
/// A stealer handle of a worker queue.
///
/// Stealers can be shared among threads.
///
/// Task schedulers typically have a single worker queue per worker thread.
///
/// # Examples
///
/// ```
/// use crossbeam_deque::{Steal, Worker};
///
/// let w = Worker::new_lifo();
/// w.push(1);
/// w.push(2);
///
/// let s = w.stealer();
/// assert_eq!(s.steal(), Steal::Success(1));
/// assert_eq!(s.steal(), Steal::Success(2));
/// assert_eq!(s.steal(), Steal::Empty);
/// ```
pub struct Stealer<T> {
/// A reference to the inner representation of the queue.
inner: Arc<CachePadded<Inner<T>>>,
/// The flavor of the queue.
flavor: Flavor,
}
unsafe impl<T: Send> Send for Stealer<T> {}
unsafe impl<T: Send> Sync for Stealer<T> {}
impl<T> Stealer<T> {
/// Returns `true` if the queue is empty.
///
/// ```
/// use crossbeam_deque::Worker;
///
/// let w = Worker::new_lifo();
/// let s = w.stealer();
///
/// assert!(s.is_empty());
/// w.push(1);
/// assert!(!s.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
let f = self.inner.front.load(Ordering::Acquire);
atomic::fence(Ordering::SeqCst);
let b = self.inner.back.load(Ordering::Acquire);
b.wrapping_sub(f) <= 0
}
/// Returns the number of tasks in the deque.
///
/// ```
/// use crossbeam_deque::Worker;
///
/// let w = Worker::new_lifo();
/// let s = w.stealer();
///
/// assert_eq!(s.len(), 0);
/// w.push(1);
/// assert_eq!(s.len(), 1);
/// w.push(2);
/// assert_eq!(s.len(), 2);
/// ```
pub fn len(&self) -> usize {
let f = self.inner.front.load(Ordering::Acquire);
atomic::fence(Ordering::SeqCst);
let b = self.inner.back.load(Ordering::Acquire);
b.wrapping_sub(f).max(0) as usize
}
/// Steals a task from the queue.
///
/// # Examples
///
/// ```
/// use crossbeam_deque::{Steal, Worker};
///
/// let w = Worker::new_lifo();
/// w.push(1);
/// w.push(2);
///
/// let s = w.stealer();
/// assert_eq!(s.steal(), Steal::Success(1));
/// assert_eq!(s.steal(), Steal::Success(2));
/// ```
pub fn steal(&self) -> Steal<T> {
// Load the front index.
let f = self.inner.front.load(Ordering::Acquire);
// A SeqCst fence is needed here.
//
// If the current thread is already pinned (reentrantly), we must manually issue the
// fence. Otherwise, the following pinning will issue the fence anyway, so we don't
// have to.
if epoch::is_pinned() {
atomic::fence(Ordering::SeqCst);
}
let guard = &epoch::pin();
// Load the back index.
let b = self.inner.back.load(Ordering::Acquire);
// Is the queue empty?
if b.wrapping_sub(f) <= 0 {
return Steal::Empty;
}
// Load the buffer and read the task at the front.
let buffer = self.inner.buffer.load(Ordering::Acquire, guard);
let task = unsafe { buffer.deref().read(f) };
// Try incrementing the front index to steal the task.
// If the buffer has been swapped or the increment fails, we retry.
if self.inner.buffer.load(Ordering::Acquire, guard) != buffer
|| self
.inner
.front
.compare_exchange(f, f.wrapping_add(1), Ordering::SeqCst, Ordering::Relaxed)
.is_err()
{
// We didn't steal this task, forget it.
mem::forget(task);
return Steal::Retry;
}
// Return the stolen task.
Steal::Success(task)
}
/// Steals a batch of tasks and pushes them into another worker.
///
/// How many tasks exactly will be stolen is not specified. That said, this method will try to
/// steal around half of the tasks in the queue, but also not more than some constant limit.
///
/// # Examples
///
/// ```
/// use crossbeam_deque::Worker;
///
/// let w1 = Worker::new_fifo();
/// w1.push(1);
/// w1.push(2);
/// w1.push(3);
/// w1.push(4);
///
/// let s = w1.stealer();
/// let w2 = Worker::new_fifo();
///
/// let _ = s.steal_batch(&w2);
/// assert_eq!(w2.pop(), Some(1));
/// assert_eq!(w2.pop(), Some(2));
/// ```
pub fn steal_batch(&self, dest: &Worker<T>) -> Steal<()> {
if Arc::ptr_eq(&self.inner, &dest.inner) {
if dest.is_empty() {
return Steal::Empty;
} else {
return Steal::Success(());
}
}
// Load the front index.
let mut f = self.inner.front.load(Ordering::Acquire);
// A SeqCst fence is needed here.
//
// If the current thread is already pinned (reentrantly), we must manually issue the
// fence. Otherwise, the following pinning will issue the fence anyway, so we don't
// have to.
if epoch::is_pinned() {
atomic::fence(Ordering::SeqCst);
}
let guard = &epoch::pin();
// Load the back index.
let b = self.inner.back.load(Ordering::Acquire);
// Is the queue empty?
let len = b.wrapping_sub(f);
if len <= 0 {
return Steal::Empty;
}
// Reserve capacity for the stolen batch.
let batch_size = cmp::min((len as usize + 1) / 2, MAX_BATCH);
dest.reserve(batch_size);
let mut batch_size = batch_size as isize;
// Get the destination buffer and back index.
let dest_buffer = dest.buffer.get();
let mut dest_b = dest.inner.back.load(Ordering::Relaxed);
// Load the buffer.
let buffer = self.inner.buffer.load(Ordering::Acquire, guard);
match self.flavor {
// Steal a batch of tasks from the front at once.
Flavor::Fifo => {
// Copy the batch from the source to the destination buffer.
match dest.flavor {
Flavor::Fifo => {
for i in 0..batch_size {
unsafe {
let task = buffer.deref().read(f.wrapping_add(i));
dest_buffer.write(dest_b.wrapping_add(i), task);
}
}
}
Flavor::Lifo => {
for i in 0..batch_size {
unsafe {
let task = buffer.deref().read(f.wrapping_add(i));
dest_buffer.write(dest_b.wrapping_add(batch_size - 1 - i), task);
}
}
}
}
// Try incrementing the front index to steal the batch.
// If the buffer has been swapped or the increment fails, we retry.
if self.inner.buffer.load(Ordering::Acquire, guard) != buffer
|| self
.inner
.front
.compare_exchange(
f,
f.wrapping_add(batch_size),
Ordering::SeqCst,
Ordering::Relaxed,
)
.is_err()
{
return Steal::Retry;
}
dest_b = dest_b.wrapping_add(batch_size);
}
// Steal a batch of tasks from the front one by one.
Flavor::Lifo => {
// This loop may modify the batch_size, which triggers a clippy lint warning.
// Use a new variable to avoid the warning, and to make it clear we aren't
// modifying the loop exit condition during iteration.
let original_batch_size = batch_size;
for i in 0..original_batch_size {
// If this is not the first steal, check whether the queue is empty.
if i > 0 {
// We've already got the current front index. Now execute the fence to
// synchronize with other threads.
atomic::fence(Ordering::SeqCst);
// Load the back index.
let b = self.inner.back.load(Ordering::Acquire);
// Is the queue empty?
if b.wrapping_sub(f) <= 0 {
batch_size = i;
break;
}
}
// Read the task at the front.
let task = unsafe { buffer.deref().read(f) };
// Try incrementing the front index to steal the task.
// If the buffer has been swapped or the increment fails, we retry.
if self.inner.buffer.load(Ordering::Acquire, guard) != buffer
|| self
.inner
.front
.compare_exchange(
f,
f.wrapping_add(1),
Ordering::SeqCst,
Ordering::Relaxed,
)
.is_err()
{
// We didn't steal this task, forget it and break from the loop.
mem::forget(task);
batch_size = i;
break;
}
// Write the stolen task into the destination buffer.
unsafe {
dest_buffer.write(dest_b, task);
}
// Move the source front index and the destination back index one step forward.
f = f.wrapping_add(1);
dest_b = dest_b.wrapping_add(1);
}
// If we didn't steal anything, the operation needs to be retried.
if batch_size == 0 {
return Steal::Retry;
}
// If stealing into a FIFO queue, stolen tasks need to be reversed.
if dest.flavor == Flavor::Fifo {
for i in 0..batch_size / 2 {
unsafe {
let i1 = dest_b.wrapping_sub(batch_size - i);
let i2 = dest_b.wrapping_sub(i + 1);
let t1 = dest_buffer.read(i1);
let t2 = dest_buffer.read(i2);
dest_buffer.write(i1, t2);
dest_buffer.write(i2, t1);
}
}
}
}
}
atomic::fence(Ordering::Release);
// Update the back index in the destination queue.
//
// This ordering could be `Relaxed`, but then thread sanitizer would falsely report data
// races because it doesn't understand fences.
dest.inner.back.store(dest_b, Ordering::Release);
// Return with success.
Steal::Success(())
}
/// Steals a batch of tasks, pushes them into another worker, and pops a task from that worker.
///
/// How many tasks exactly will be stolen is not specified. That said, this method will try to
/// steal around half of the tasks in the queue, but also not more than some constant limit.
///
/// # Examples
///
/// ```
/// use crossbeam_deque::{Steal, Worker};
///
/// let w1 = Worker::new_fifo();
/// w1.push(1);
/// w1.push(2);
/// w1.push(3);
/// w1.push(4);
///
/// let s = w1.stealer();
/// let w2 = Worker::new_fifo();
///
/// assert_eq!(s.steal_batch_and_pop(&w2), Steal::Success(1));
/// assert_eq!(w2.pop(), Some(2));
/// ```
pub fn steal_batch_and_pop(&self, dest: &Worker<T>) -> Steal<T> {
if Arc::ptr_eq(&self.inner, &dest.inner) {
match dest.pop() {
None => return Steal::Empty,
Some(task) => return Steal::Success(task),
}
}
// Load the front index.
let mut f = self.inner.front.load(Ordering::Acquire);
// A SeqCst fence is needed here.
//
// If the current thread is already pinned (reentrantly), we must manually issue the
// fence. Otherwise, the following pinning will issue the fence anyway, so we don't
// have to.
if epoch::is_pinned() {
atomic::fence(Ordering::SeqCst);
}
let guard = &epoch::pin();
// Load the back index.
let b = self.inner.back.load(Ordering::Acquire);
// Is the queue empty?
let len = b.wrapping_sub(f);
if len <= 0 {
return Steal::Empty;
}
// Reserve capacity for the stolen batch.
let batch_size = cmp::min((len as usize - 1) / 2, MAX_BATCH - 1);
dest.reserve(batch_size);
let mut batch_size = batch_size as isize;
// Get the destination buffer and back index.
let dest_buffer = dest.buffer.get();
let mut dest_b = dest.inner.back.load(Ordering::Relaxed);
// Load the buffer
let buffer = self.inner.buffer.load(Ordering::Acquire, guard);
// Read the task at the front.
let mut task = unsafe { buffer.deref().read(f) };
match self.flavor {
// Steal a batch of tasks from the front at once.
Flavor::Fifo => {
// Copy the batch from the source to the destination buffer.
match dest.flavor {
Flavor::Fifo => {
for i in 0..batch_size {
unsafe {
let task = buffer.deref().read(f.wrapping_add(i + 1));
dest_buffer.write(dest_b.wrapping_add(i), task);
}
}
}
Flavor::Lifo => {
for i in 0..batch_size {
unsafe {
let task = buffer.deref().read(f.wrapping_add(i + 1));
dest_buffer.write(dest_b.wrapping_add(batch_size - 1 - i), task);
}
}
}
}
// Try incrementing the front index to steal the task.
// If the buffer has been swapped or the increment fails, we retry.
if self.inner.buffer.load(Ordering::Acquire, guard) != buffer
|| self
.inner
.front
.compare_exchange(
f,
f.wrapping_add(batch_size + 1),
Ordering::SeqCst,
Ordering::Relaxed,
)
.is_err()
{
// We didn't steal this task, forget it.
mem::forget(task);
return Steal::Retry;
}
dest_b = dest_b.wrapping_add(batch_size);
}
// Steal a batch of tasks from the front one by one.
Flavor::Lifo => {
// Try incrementing the front index to steal the task.
if self
.inner
.front
.compare_exchange(f, f.wrapping_add(1), Ordering::SeqCst, Ordering::Relaxed)
.is_err()
{
// We didn't steal this task, forget it.
mem::forget(task);
return Steal::Retry;
}
// Move the front index one step forward.
f = f.wrapping_add(1);