Debian Codegraph @

third_party/rust/crossbeam-queue/src/seg_queue.rs

raw
1 use alloc::boxed::Box;
2 use core::cell::UnsafeCell;
3 use core::fmt;
4 use core::marker::PhantomData;
5 use core::mem::MaybeUninit;
6 use core::ptr;
7 use core::sync::atomic::{self, AtomicPtr, AtomicUsize, Ordering};
8
9 use crossbeam_utils::{Backoff, CachePadded};
10
11 // Bits indicating the state of a slot:
12 // * If a value has been written into the slot, `WRITE` is set.
13 // * If a value has been read from the slot, `READ` is set.
14 // * If the block is being destroyed, `DESTROY` is set.
15 const WRITE: usize = 1;
16 const READ: usize = 2;
17 const DESTROY: usize = 4;
18
19 // Each block covers one "lap" of indices.
20 const LAP: usize = 32;
21 // The maximum number of values a block can hold.
22 const BLOCK_CAP: usize = LAP - 1;
23 // How many lower bits are reserved for metadata.
24 const SHIFT: usize = 1;
25 // Indicates that the block is not the last one.
26 const HAS_NEXT: usize = 1;
27
28 /// A slot in a block.
29 struct Slot<T> {
30 /// The value.
31 value: UnsafeCell<MaybeUninit<T>>,
32
33 /// The state of the slot.
34 state: AtomicUsize,
35 }
36
37 impl<T> Slot<T> {
38 const UNINIT: Self = Self {
39 value: UnsafeCell::new(MaybeUninit::uninit()),
40 state: AtomicUsize::new(0),
41 };
42
43 /// Waits until a value is written into the slot.
44 fn wait_write(&self) {
45 let backoff = Backoff::new();
46 while self.state.load(Ordering::Acquire) & WRITE == 0 {
47 backoff.snooze();
48 }
49 }
50 }
51
52 /// A block in a linked list.
53 ///
54 /// Each block in the list can hold up to `BLOCK_CAP` values.
55 struct Block<T> {
56 /// The next block in the linked list.
57 next: AtomicPtr<Block<T>>,
58
59 /// Slots for values.
60 slots: [Slot<T>; BLOCK_CAP],
61 }
62
63 impl<T> Block<T> {
64 /// Creates an empty block that starts at `start_index`.
65 fn new() -> Block<T> {
66 Self {
67 next: AtomicPtr::new(ptr::null_mut()),
68 slots: [Slot::UNINIT; BLOCK_CAP],
69 }
70 }
71
72 /// Waits until the next pointer is set.
73 fn wait_next(&self) -> *mut Block<T> {
74 let backoff = Backoff::new();
75 loop {
76 let next = self.next.load(Ordering::Acquire);
77 if !next.is_null() {
78 return next;
79 }
80 backoff.snooze();
81 }
82 }
83
84 /// Sets the `DESTROY` bit in slots starting from `start` and destroys the block.
85 unsafe fn destroy(this: *mut Block<T>, start: usize) {
86 // It is not necessary to set the `DESTROY` bit in the last slot because that slot has
87 // begun destruction of the block.
88 for i in start..BLOCK_CAP - 1 {
89 let slot = (*this).slots.get_unchecked(i);
90
91 // Mark the `DESTROY` bit if a thread is still using the slot.
92 if slot.state.load(Ordering::Acquire) & READ == 0
93 && slot.state.fetch_or(DESTROY, Ordering::AcqRel) & READ == 0
94 {
95 // If a thread is still using the slot, it will continue destruction of the block.
96 return;
97 }
98 }
99
100 // No thread is using the block, now it is safe to destroy it.
101 drop(Box::from_raw(this));
102 }
103 }
104
105 /// A position in a queue.
106 struct Position<T> {
107 /// The index in the queue.
108 index: AtomicUsize,
109
110 /// The block in the linked list.
111 block: AtomicPtr<Block<T>>,
112 }
113
114 /// An unbounded multi-producer multi-consumer queue.
115 ///
116 /// This queue is implemented as a linked list of segments, where each segment is a small buffer
117 /// that can hold a handful of elements. There is no limit to how many elements can be in the queue
118 /// at a time. However, since segments need to be dynamically allocated as elements get pushed,
119 /// this queue is somewhat slower than [`ArrayQueue`].
120 ///
121 /// [`ArrayQueue`]: super::ArrayQueue
122 ///
123 /// # Examples
124 ///
125 /// ```
126 /// use crossbeam_queue::SegQueue;
127 ///
128 /// let q = SegQueue::new();
129 ///
130 /// q.push('a');
131 /// q.push('b');
132 ///
133 /// assert_eq!(q.pop(), Some('a'));
134 /// assert_eq!(q.pop(), Some('b'));
135 /// assert!(q.pop().is_none());
136 /// ```
137 pub struct SegQueue<T> {
138 /// The head of the queue.
139 head: CachePadded<Position<T>>,
140
141 /// The tail of the queue.
142 tail: CachePadded<Position<T>>,
143
144 /// Indicates that dropping a `SegQueue<T>` may drop values of type `T`.
145 _marker: PhantomData<T>,
146 }
147
148 unsafe impl<T: Send> Send for SegQueue<T> {}
149 unsafe impl<T: Send> Sync for SegQueue<T> {}
150
151 impl<T> SegQueue<T> {
152 /// Creates a new unbounded queue.
153 ///
154 /// # Examples
155 ///
156 /// ```
157 /// use crossbeam_queue::SegQueue;
158 ///
159 /// let q = SegQueue::<i32>::new();
160 /// ```
161 pub const fn new() -> SegQueue<T> {
162 SegQueue {
163 head: CachePadded::new(Position {
164 block: AtomicPtr::new(ptr::null_mut()),
165 index: AtomicUsize::new(0),
166 }),
167 tail: CachePadded::new(Position {
168 block: AtomicPtr::new(ptr::null_mut()),
169 index: AtomicUsize::new(0),
170 }),
171 _marker: PhantomData,
172 }
173 }
174
175 /// Pushes an element into the queue.
176 ///
177 /// # Examples
178 ///
179 /// ```
180 /// use crossbeam_queue::SegQueue;
181 ///
182 /// let q = SegQueue::new();
183 ///
184 /// q.push(10);
185 /// q.push(20);
186 /// ```
187 pub fn push(&self, value: T) {
188 let backoff = Backoff::new();
189 let mut tail = self.tail.index.load(Ordering::Acquire);
190 let mut block = self.tail.block.load(Ordering::Acquire);
191 let mut next_block = None;
192
193 loop {
194 // Calculate the offset of the index into the block.
195 let offset = (tail >> SHIFT) % LAP;
196
197 // If we reached the end of the block, wait until the next one is installed.
198 if offset == BLOCK_CAP {
199 backoff.snooze();
200 tail = self.tail.index.load(Ordering::Acquire);
201 block = self.tail.block.load(Ordering::Acquire);
202 continue;
203 }
204
205 // If we're going to have to install the next block, allocate it in advance in order to
206 // make the wait for other threads as short as possible.
207 if offset + 1 == BLOCK_CAP && next_block.is_none() {
208 next_block = Some(Box::new(Block::<T>::new()));
209 }
210
211 // If this is the first push operation, we need to allocate the first block.
212 if block.is_null() {
213 let new = Box::into_raw(Box::new(Block::<T>::new()));
214
215 if self
216 .tail
217 .block
218 .compare_exchange(block, new, Ordering::Release, Ordering::Relaxed)
219 .is_ok()
220 {
221 self.head.block.store(new, Ordering::Release);
222 block = new;
223 } else {
224 next_block = unsafe { Some(Box::from_raw(new)) };
225 tail = self.tail.index.load(Ordering::Acquire);
226 block = self.tail.block.load(Ordering::Acquire);
227 continue;
228 }
229 }
230
231 let new_tail = tail + (1 << SHIFT);
232
233 // Try advancing the tail forward.
234 match self.tail.index.compare_exchange_weak(
235 tail,
236 new_tail,
237 Ordering::SeqCst,
238 Ordering::Acquire,
239 ) {
240 Ok(_) => unsafe {
241 // If we've reached the end of the block, install the next one.
242 if offset + 1 == BLOCK_CAP {
243 let next_block = Box::into_raw(next_block.unwrap());
244 let next_index = new_tail.wrapping_add(1 << SHIFT);
245
246 self.tail.block.store(next_block, Ordering::Release);
247 self.tail.index.store(next_index, Ordering::Release);
248 (*block).next.store(next_block, Ordering::Release);
249 }
250
251 // Write the value into the slot.
252 let slot = (*block).slots.get_unchecked(offset);
253 slot.value.get().write(MaybeUninit::new(value));
254 slot.state.fetch_or(WRITE, Ordering::Release);
255
256 return;
257 },
258 Err(t) => {
259 tail = t;
260 block = self.tail.block.load(Ordering::Acquire);
261 backoff.spin();
262 }
263 }
264 }
265 }
266
267 /// Pops an element from the queue.
268 ///
269 /// If the queue is empty, `None` is returned.
270 ///
271 /// # Examples
272 ///
273 /// ```
274 /// use crossbeam_queue::SegQueue;
275 ///
276 /// let q = SegQueue::new();
277 ///
278 /// q.push(10);
279 /// assert_eq!(q.pop(), Some(10));
280 /// assert!(q.pop().is_none());
281 /// ```
282 pub fn pop(&self) -> Option<T> {
283 let backoff = Backoff::new();
284 let mut head = self.head.index.load(Ordering::Acquire);
285 let mut block = self.head.block.load(Ordering::Acquire);
286
287 loop {
288 // Calculate the offset of the index into the block.
289 let offset = (head >> SHIFT) % LAP;
290
291 // If we reached the end of the block, wait until the next one is installed.
292 if offset == BLOCK_CAP {
293 backoff.snooze();
294 head = self.head.index.load(Ordering::Acquire);
295 block = self.head.block.load(Ordering::Acquire);
296 continue;
297 }
298
299 let mut new_head = head + (1 << SHIFT);
300
301 if new_head & HAS_NEXT == 0 {
302 atomic::fence(Ordering::SeqCst);
303 let tail = self.tail.index.load(Ordering::Relaxed);
304
305 // If the tail equals the head, that means the queue is empty.
306 if head >> SHIFT == tail >> SHIFT {
307 return None;
308 }
309
310 // If head and tail are not in the same block, set `HAS_NEXT` in head.
311 if (head >> SHIFT) / LAP != (tail >> SHIFT) / LAP {
312 new_head |= HAS_NEXT;
313 }
314 }
315
316 // The block can be null here only if the first push operation is in progress. In that
317 // case, just wait until it gets initialized.
318 if block.is_null() {
319 backoff.snooze();
320 head = self.head.index.load(Ordering::Acquire);
321 block = self.head.block.load(Ordering::Acquire);
322 continue;
323 }
324
325 // Try moving the head index forward.
326 match self.head.index.compare_exchange_weak(
327 head,
328 new_head,
329 Ordering::SeqCst,
330 Ordering::Acquire,
331 ) {
332 Ok(_) => unsafe {
333 // If we've reached the end of the block, move to the next one.
334 if offset + 1 == BLOCK_CAP {
335 let next = (*block).wait_next();
336 let mut next_index = (new_head & !HAS_NEXT).wrapping_add(1 << SHIFT);
337 if !(*next).next.load(Ordering::Relaxed).is_null() {
338 next_index |= HAS_NEXT;
339 }
340
341 self.head.block.store(next, Ordering::Release);
342 self.head.index.store(next_index, Ordering::Release);
343 }
344
345 // Read the value.
346 let slot = (*block).slots.get_unchecked(offset);
347 slot.wait_write();
348 let value = slot.value.get().read().assume_init();
349
350 // Destroy the block if we've reached the end, or if another thread wanted to
351 // destroy but couldn't because we were busy reading from the slot.
352 if offset + 1 == BLOCK_CAP {
353 Block::destroy(block, 0);
354 } else if slot.state.fetch_or(READ, Ordering::AcqRel) & DESTROY != 0 {
355 Block::destroy(block, offset + 1);
356 }
357
358 return Some(value);
359 },
360 Err(h) => {
361 head = h;
362 block = self.head.block.load(Ordering::Acquire);
363 backoff.spin();
364 }
365 }
366 }
367 }
368
369 /// Returns `true` if the queue is empty.
370 ///
371 /// # Examples
372 ///
373 /// ```
374 /// use crossbeam_queue::SegQueue;
375 ///
376 /// let q = SegQueue::new();
377 ///
378 /// assert!(q.is_empty());
379 /// q.push(1);
380 /// assert!(!q.is_empty());
381 /// ```
382 pub fn is_empty(&self) -> bool {
383 let head = self.head.index.load(Ordering::SeqCst);
384 let tail = self.tail.index.load(Ordering::SeqCst);
385 head >> SHIFT == tail >> SHIFT
386 }
387
388 /// Returns the number of elements in the queue.
389 ///
390 /// # Examples
391 ///
392 /// ```
393 /// use crossbeam_queue::SegQueue;
394 ///
395 /// let q = SegQueue::new();
396 /// assert_eq!(q.len(), 0);
397 ///
398 /// q.push(10);
399 /// assert_eq!(q.len(), 1);
400 ///
401 /// q.push(20);
402 /// assert_eq!(q.len(), 2);
403 /// ```
404 pub fn len(&self) -> usize {
405 loop {
406 // Load the tail index, then load the head index.
407 let mut tail = self.tail.index.load(Ordering::SeqCst);
408 let mut head = self.head.index.load(Ordering::SeqCst);
409
410 // If the tail index didn't change, we've got consistent indices to work with.
411 if self.tail.index.load(Ordering::SeqCst) == tail {
412 // Erase the lower bits.
413 tail &= !((1 << SHIFT) - 1);
414 head &= !((1 << SHIFT) - 1);
415
416 // Fix up indices if they fall onto block ends.
417 if (tail >> SHIFT) & (LAP - 1) == LAP - 1 {
418 tail = tail.wrapping_add(1 << SHIFT);
419 }
420 if (head >> SHIFT) & (LAP - 1) == LAP - 1 {
421 head = head.wrapping_add(1 << SHIFT);
422 }
423
424 // Rotate indices so that head falls into the first block.
425 let lap = (head >> SHIFT) / LAP;
426 tail = tail.wrapping_sub((lap * LAP) << SHIFT);
427 head = head.wrapping_sub((lap * LAP) << SHIFT);
428
429 // Remove the lower bits.
430 tail >>= SHIFT;
431 head >>= SHIFT;
432
433 // Return the difference minus the number of blocks between tail and head.
434 return tail - head - tail / LAP;
435 }
436 }
437 }
438 }
439
440 impl<T> Drop for SegQueue<T> {
441 fn drop(&mut self) {
442 let mut head = *self.head.index.get_mut();
443 let mut tail = *self.tail.index.get_mut();
444 let mut block = *self.head.block.get_mut();
445
446 // Erase the lower bits.
447 head &= !((1 << SHIFT) - 1);
448 tail &= !((1 << SHIFT) - 1);
449
450 unsafe {
451 // Drop all values between `head` and `tail` and deallocate the heap-allocated blocks.
452 while head != tail {
453 let offset = (head >> SHIFT) % LAP;
454
455 if offset < BLOCK_CAP {
456 // Drop the value in the slot.
457 let slot = (*block).slots.get_unchecked(offset);
458 let p = &mut *slot.value.get();
459 p.as_mut_ptr().drop_in_place();
460 } else {
461 // Deallocate the block and move to the next one.
462 let next = *(*block).next.get_mut();
463 drop(Box::from_raw(block));
464 block = next;
465 }
466
467 head = head.wrapping_add(1 << SHIFT);
468 }
469
470 // Deallocate the last remaining block.
471 if !block.is_null() {
472 drop(Box::from_raw(block));
473 }
474 }
475 }
476 }
477
478 impl<T> fmt::Debug for SegQueue<T> {
479 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480 f.pad("SegQueue { .. }")
481 }
482 }
483
484 impl<T> Default for SegQueue<T> {
485 fn default() -> SegQueue<T> {
486 SegQueue::new()
487 }
488 }
489
490 impl<T> IntoIterator for SegQueue<T> {
491 type Item = T;
492
493 type IntoIter = IntoIter<T>;
494
495 fn into_iter(self) -> Self::IntoIter {
496 IntoIter { value: self }
497 }
498 }
499
500 #[derive(Debug)]
501 pub struct IntoIter<T> {
502 value: SegQueue<T>,
503 }
504
505 impl<T> Iterator for IntoIter<T> {
506 type Item = T;
507
508 fn next(&mut self) -> Option<Self::Item> {
509 let value = &mut self.value;
510 let head = *value.head.index.get_mut();
511 let tail = *value.tail.index.get_mut();
512 if head >> SHIFT == tail >> SHIFT {
513 None
514 } else {
515 let block = *value.head.block.get_mut();
516 let offset = (head >> SHIFT) % LAP;
517
518 // SAFETY: We have mutable access to this, so we can read without
519 // worrying about concurrency. Furthermore, we know this is
520 // initialized because it is the value pointed at by `value.head`
521 // and this is a non-empty queue.
522 let item = unsafe {
523 let slot = (*block).slots.get_unchecked(offset);
524 let p = &mut *slot.value.get();
525 p.as_mut_ptr().read()
526 };
527 if offset + 1 == BLOCK_CAP {
528 // Deallocate the block and move to the next one.
529 // SAFETY: The block is initialized because we've been reading
530 // from it this entire time. We can drop it b/c everything has
531 // been read out of it, so nothing is pointing to it anymore.
532 unsafe {
533 let next = *(*block).next.get_mut();
534 drop(Box::from_raw(block));
535 *value.head.block.get_mut() = next;
536 }
537 // The last value in a block is empty, so skip it
538 *value.head.index.get_mut() = head.wrapping_add(2 << SHIFT);
539 // Double-check that we're pointing to the first item in a block.
540 debug_assert_eq!((*value.head.index.get_mut() >> SHIFT) % LAP, 0);
541 } else {
542 *value.head.index.get_mut() = head.wrapping_add(1 << SHIFT);
543 }
544 Some(item)
545 }
546 }
547 }