22e94e076832962350beca3301a12d79628eed53
[folly.git] / folly / concurrency / UnboundedQueue.h
1 /*
2  * Copyright 2017-present Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <atomic>
20 #include <chrono>
21 #include <memory>
22
23 #include <glog/logging.h>
24
25 #include <folly/concurrency/CacheLocality.h>
26 #include <folly/experimental/hazptr/hazptr.h>
27 #include <folly/synchronization/SaturatingSemaphore.h>
28
29 namespace folly {
30
31 /// UnboundedQueue supports a variety of options for unbounded
32 /// dynamically expanding an shrinking queues, including variations of:
33 /// - Single vs. multiple producers
34 /// - Single vs. multiple consumers
35 /// - Blocking vs. spin-waiting
36 /// - Non-waiting, timed, and waiting consumer operations.
37 /// Producer operations never wait or fail (unless out-of-memory).
38 ///
39 /// Template parameters:
40 /// - T: element type
41 /// - SingleProducer: true if there can be only one producer at a
42 ///   time.
43 /// - SingleConsumer: true if there can be only one consumer at a
44 ///   time.
45 /// - MayBlock: true if consumers may block, false if they only
46 ///   spin. A performance tuning parameter.
47 /// - LgSegmentSize (default 8): Log base 2 of number of elements per
48 ///   segment. A performance tuning parameter. See below.
49 /// - LgAlign (default 7): Log base 2 of alignment directive; can be
50 ///   used to balance scalability (avoidance of false sharing) with
51 ///   memory efficiency.
52 ///
53 /// When to use UnboundedQueue:
54 /// - If a small bound may lead to deadlock or performance degradation
55 ///   under bursty patterns.
56 /// - If there is no risk of the queue growing too much.
57 ///
58 /// When not to use UnboundedQueue:
59 /// - If there is risk of the queue growing too much and a large bound
60 ///   is acceptable, then use DynamicBoundedQueue.
61 /// - If the queue must not allocate on enqueue or it must have a
62 ///   small bound, then use fixed-size MPMCQueue or (if non-blocking
63 ///   SPSC) ProducerConsumerQueue.
64 ///
65 /// Template Aliases:
66 ///   USPSCQueue<T, MayBlock, LgSegmentSize, LgAlign>
67 ///   UMPSCQueue<T, MayBlock, LgSegmentSize, LgAlign>
68 ///   USPMCQueue<T, MayBlock, LgSegmentSize, LgAlign>
69 ///   UMPMCQueue<T, MayBlock, LgSegmentSize, LgAlign>
70 ///
71 /// Functions:
72 ///   Producer operations never wait or fail (unless OOM)
73 ///     void enqueue(const T&);
74 ///     void enqueue(T&&);
75 ///         Adds an element to the end of the queue.
76 ///
77 ///   Consumer operations:
78 ///     void dequeue(T&);
79 ///         Extracts an element from the front of the queue. Waits
80 ///         until an element is available if needed.
81 ///     bool try_dequeue(T&);
82 ///         Tries to extract an element from the front of the queue
83 ///         if available. Returns true if successful, false otherwise.
84 ///     bool try_dequeue_until(T&, time_point& deadline);
85 ///         Tries to extract an element from the front of the queue
86 ///         if available until the specified deadline.  Returns true
87 ///         if successful, false otherwise.
88 ///     bool try_dequeue_for(T&, duration&);
89 ///         Tries to extract an element from the front of the queue if
90 ///         available for until the expiration of the specified
91 ///         duration.  Returns true if successful, false otherwise.
92 ///
93 ///   Secondary functions:
94 ///     size_t size();
95 ///         Returns an estimate of the size of the queue.
96 ///     bool empty();
97 ///         Returns true only if the queue was empty during the call.
98 ///     Note: size() and empty() are guaranteed to be accurate only if
99 ///     the queue is not changed concurrently.
100 ///
101 /// Usage examples:
102 /// @code
103 ///   /* UMPSC, doesn't block, 1024 int elements per segment */
104 ///   UMPSCQueue<int, false, 10> q;
105 ///   q.enqueue(1);
106 ///   q.enqueue(2);
107 ///   q.enqueue(3);
108 ///   ASSERT_FALSE(q.empty());
109 ///   ASSERT_EQ(q.size(), 3);
110 ///   int v;
111 ///   q.dequeue(v);
112 ///   ASSERT_EQ(v, 1);
113 ///   ASSERT_TRUE(try_dequeue(v));
114 ///   ASSERT_EQ(v, 2);
115 ///   ASSERT_TRUE(try_dequeue_until(v, now() + seconds(1)));
116 ///   ASSERT_EQ(v, 3);
117 ///   ASSERT_TRUE(q.empty());
118 ///   ASSERT_EQ(q.size(), 0);
119 ///   ASSERT_FALSE(try_dequeue(v));
120 ///   ASSERT_FALSE(try_dequeue_for(v, microseconds(100)));
121 /// @endcode
122 ///
123 /// Design:
124 /// - The queue is composed of one or more segments. Each segment has
125 ///   a fixed size of 2^LgSegmentSize entries. Each segment is used
126 ///   exactly once.
127 /// - Each entry is composed of a futex and a single element.
128 /// - The queue contains two 64-bit ticket variables. The producer
129 ///   ticket counts the number of producer tickets issued so far, and
130 ///   the same for the consumer ticket. Each ticket number corresponds
131 ///   to a specific entry in a specific segment.
132 /// - The queue maintains two pointers, head and tail. Head points to
133 ///   the segment that corresponds to the current consumer
134 ///   ticket. Similarly, tail pointer points to the segment that
135 ///   corresponds to the producer ticket.
136 /// - Segments are organized as a singly linked list.
137 /// - The producer with the first ticket in the current producer
138 ///   segment is solely responsible for allocating and linking the
139 ///   next segment.
140 /// - The producer with the last ticket in the current producer
141 ///   segment is solely responsible for advancing the tail pointer to
142 ///   the next segment.
143 /// - Similarly, the consumer with the last ticket in the current
144 ///   consumer segment is solely responsible for advancing the head
145 ///   pointer to the next segment. It must ensure that head never
146 ///   overtakes tail.
147 ///
148 /// Memory Usage:
149 /// - An empty queue contains one segment. A nonempty queue contains
150 ///   one or two more segment than fits its contents.
151 /// - Removed segments are not reclaimed until there are no threads,
152 ///   producers or consumers, have references to them or their
153 ///   predecessors. That is, a lagging thread may delay the reclamation
154 ///   of a chain of removed segments.
155 /// - The template parameter LgAlign can be used to reduce memory usage
156 ///   at the cost of increased chance of false sharing.
157 ///
158 /// Performance considerations:
159 /// - All operations take constant time, excluding the costs of
160 ///   allocation, reclamation, interference from other threads, and
161 ///   waiting for actions by other threads.
162 /// - In general, using the single producer and or single consumer
163 ///   variants yield better performance than the MP and MC
164 ///   alternatives.
165 /// - SPSC without blocking is the fastest configuration. It doesn't
166 ///   include any read-modify-write atomic operations, full fences, or
167 ///   system calls in the critical path.
168 /// - MP adds a fetch_add to the critical path of each producer operation.
169 /// - MC adds a fetch_add or compare_exchange to the critical path of
170 ///   each consumer operation.
171 /// - The possibility of consumers blocking, even if they never do,
172 ///   adds a compare_exchange to the critical path of each producer
173 ///   operation.
174 /// - MPMC, SPMC, MPSC require the use of a deferred reclamation
175 ///   mechanism to guarantee that segments removed from the linked
176 ///   list, i.e., unreachable from the head pointer, are reclaimed
177 ///   only after they are no longer needed by any lagging producers or
178 ///   consumers.
179 /// - The overheads of segment allocation and reclamation are intended
180 ///   to be mostly out of the critical path of the queue's throughput.
181 /// - If the template parameter LgSegmentSize is changed, it should be
182 ///   set adequately high to keep the amortized cost of allocation and
183 ///   reclamation low.
184 /// - Another consideration is that the queue is guaranteed to have
185 ///   enough space for a number of consumers equal to 2^LgSegmentSize
186 ///   for local blocking. Excess waiting consumers spin.
187 /// - It is recommended to measure performance with different variants
188 ///   when applicable, e.g., UMPMC vs UMPSC. Depending on the use
189 ///   case, sometimes the variant with the higher sequential overhead
190 ///   may yield better results due to, for example, more favorable
191 ///   producer-consumer balance or favorable timing for avoiding
192 ///   costly blocking.
193
194 template <
195     typename T,
196     bool SingleProducer,
197     bool SingleConsumer,
198     bool MayBlock,
199     size_t LgSegmentSize = 8,
200     size_t LgAlign = 7,
201     template <typename> class Atom = std::atomic>
202 class UnboundedQueue {
203   using Ticket = uint64_t;
204   class Entry;
205   class Segment;
206
207   static constexpr bool SPSC = SingleProducer && SingleConsumer;
208   static constexpr size_t Stride = SPSC || (LgSegmentSize <= 1) ? 1 : 27;
209   static constexpr size_t SegmentSize = 1u << LgSegmentSize;
210   static constexpr size_t Align = 1u << LgAlign;
211
212   static_assert(
213       std::is_nothrow_destructible<T>::value,
214       "T must be nothrow_destructible");
215   static_assert((Stride & 1) == 1, "Stride must be odd");
216   static_assert(LgSegmentSize < 32, "LgSegmentSize must be < 32");
217   static_assert(LgAlign < 16, "LgAlign must be < 16");
218
219   struct Consumer {
220     Atom<Segment*> head;
221     Atom<Ticket> ticket;
222   };
223   struct Producer {
224     Atom<Segment*> tail;
225     Atom<Ticket> ticket;
226   };
227
228   alignas(Align) Consumer c_;
229   alignas(Align) Producer p_;
230
231  public:
232   /** constructor */
233   UnboundedQueue() {
234     setProducerTicket(0);
235     setConsumerTicket(0);
236     Segment* s = new Segment(0);
237     setTail(s);
238     setHead(s);
239   }
240
241   /** destructor */
242   ~UnboundedQueue() {
243     Segment* next;
244     for (Segment* s = head(); s; s = next) {
245       next = s->nextSegment();
246       reclaimSegment(s);
247     }
248   }
249
250   /** enqueue */
251   FOLLY_ALWAYS_INLINE void enqueue(const T& arg) {
252     enqueueImpl(arg);
253   }
254
255   FOLLY_ALWAYS_INLINE void enqueue(T&& arg) {
256     enqueueImpl(std::move(arg));
257   }
258
259   /** dequeue */
260   FOLLY_ALWAYS_INLINE void dequeue(T& item) noexcept {
261     dequeueImpl(item);
262   }
263
264   /** try_dequeue */
265   FOLLY_ALWAYS_INLINE bool try_dequeue(T& item) noexcept {
266     return tryDequeueUntil(item, std::chrono::steady_clock::time_point::min());
267   }
268
269   /** try_dequeue_until */
270   template <typename Clock, typename Duration>
271   FOLLY_ALWAYS_INLINE bool try_dequeue_until(
272       T& item,
273       const std::chrono::time_point<Clock, Duration>& deadline) noexcept {
274     return tryDequeueUntil(item, deadline);
275   }
276
277   /** try_dequeue_for */
278   template <typename Rep, typename Period>
279   FOLLY_ALWAYS_INLINE bool try_dequeue_for(
280       T& item,
281       const std::chrono::duration<Rep, Period>& duration) noexcept {
282     if (LIKELY(try_dequeue(item))) {
283       return true;
284     }
285     return tryDequeueUntil(item, std::chrono::steady_clock::now() + duration);
286   }
287
288   /** size */
289   size_t size() const noexcept {
290     auto p = producerTicket();
291     auto c = consumerTicket();
292     return p > c ? p - c : 0;
293   }
294
295   /** empty */
296   bool empty() const noexcept {
297     auto c = consumerTicket();
298     auto p = producerTicket();
299     return p <= c;
300   }
301
302  private:
303   /** enqueueImpl */
304   template <typename Arg>
305   FOLLY_ALWAYS_INLINE void enqueueImpl(Arg&& arg) {
306     if (SPSC) {
307       Segment* s = tail();
308       enqueueCommon(s, std::forward<Arg>(arg));
309     } else {
310       // Using hazptr_holder instead of hazptr_local because it is
311       // possible that the T ctor happens to use hazard pointers.
312       folly::hazptr::hazptr_holder hptr;
313       Segment* s = hptr.get_protected(p_.tail);
314       enqueueCommon(s, std::forward<Arg>(arg));
315     }
316   }
317
318   /** enqueueCommon */
319   template <typename Arg>
320   FOLLY_ALWAYS_INLINE void enqueueCommon(Segment* s, Arg&& arg) {
321     Ticket t = fetchIncrementProducerTicket();
322     if (!SingleProducer) {
323       s = findSegment(s, t);
324     }
325     DCHECK_GE(t, s->minTicket());
326     DCHECK_LT(t, s->minTicket() + SegmentSize);
327     size_t idx = index(t);
328     Entry& e = s->entry(idx);
329     e.putItem(std::forward<Arg>(arg));
330     if (responsibleForAlloc(t)) {
331       allocNextSegment(s, t + SegmentSize);
332     }
333     if (responsibleForAdvance(t)) {
334       advanceTail(s);
335     }
336   }
337
338   /** dequeueImpl */
339   FOLLY_ALWAYS_INLINE void dequeueImpl(T& item) noexcept {
340     if (SPSC) {
341       Segment* s = head();
342       dequeueCommon(s, item);
343     } else {
344       // Using hazptr_holder instead of hazptr_local because it is
345       // possible to call the T dtor and it may happen to use hazard
346       // pointers.
347       folly::hazptr::hazptr_holder hptr;
348       Segment* s = hptr.get_protected(c_.head);
349       dequeueCommon(s, item);
350     }
351   }
352
353   /** dequeueCommon */
354   FOLLY_ALWAYS_INLINE void dequeueCommon(Segment* s, T& item) noexcept {
355     Ticket t = fetchIncrementConsumerTicket();
356     if (!SingleConsumer) {
357       s = findSegment(s, t);
358     }
359     size_t idx = index(t);
360     Entry& e = s->entry(idx);
361     e.takeItem(item);
362     if (responsibleForAdvance(t)) {
363       advanceHead(s);
364     }
365   }
366
367   /** tryDequeueUntil */
368   template <typename Clock, typename Duration>
369   FOLLY_ALWAYS_INLINE bool tryDequeueUntil(
370       T& item,
371       const std::chrono::time_point<Clock, Duration>& deadline) noexcept {
372     if (SingleConsumer) {
373       Segment* s = head();
374       return tryDequeueUntilSC(s, item, deadline);
375     } else {
376       // Using hazptr_holder instead of hazptr_local because it is
377       // possible to call ~T() and it may happen to use hazard pointers.
378       folly::hazptr::hazptr_holder hptr;
379       Segment* s = hptr.get_protected(c_.head);
380       return tryDequeueUntilMC(s, item, deadline);
381     }
382   }
383
384   /** tryDequeueUntilSC */
385   template <typename Clock, typename Duration>
386   FOLLY_ALWAYS_INLINE bool tryDequeueUntilSC(
387       Segment* s,
388       T& item,
389       const std::chrono::time_point<Clock, Duration>& deadline) noexcept {
390     Ticket t = consumerTicket();
391     DCHECK_GE(t, s->minTicket());
392     DCHECK_LT(t, (s->minTicket() + SegmentSize));
393     size_t idx = index(t);
394     Entry& e = s->entry(idx);
395     if (UNLIKELY(!tryDequeueWaitElem(e, t, deadline))) {
396       return false;
397     }
398     setConsumerTicket(t + 1);
399     e.takeItem(item);
400     if (responsibleForAdvance(t)) {
401       advanceHead(s);
402     }
403     return true;
404   }
405
406   /** tryDequeueUntilMC */
407   template <typename Clock, typename Duration>
408   FOLLY_ALWAYS_INLINE bool tryDequeueUntilMC(
409       Segment* s,
410       T& item,
411       const std::chrono::time_point<Clock, Duration>& deadline) noexcept {
412     while (true) {
413       Ticket t = consumerTicket();
414       if (UNLIKELY(t >= (s->minTicket() + SegmentSize))) {
415         s = tryGetNextSegmentUntil(s, deadline);
416         if (s == nullptr) {
417           return false; // timed out
418         }
419         continue;
420       }
421       size_t idx = index(t);
422       Entry& e = s->entry(idx);
423       if (UNLIKELY(!tryDequeueWaitElem(e, t, deadline))) {
424         return false;
425       }
426       if (!c_.ticket.compare_exchange_weak(
427               t, t + 1, std::memory_order_acq_rel, std::memory_order_acquire)) {
428         continue;
429       }
430       e.takeItem(item);
431       if (responsibleForAdvance(t)) {
432         advanceHead(s);
433       }
434       return true;
435     }
436   }
437
438   /** tryDequeueWaitElem */
439   template <typename Clock, typename Duration>
440   FOLLY_ALWAYS_INLINE bool tryDequeueWaitElem(
441       Entry& e,
442       Ticket t,
443       const std::chrono::time_point<Clock, Duration>& deadline) noexcept {
444     while (true) {
445       if (LIKELY(e.tryWaitUntil(deadline))) {
446         return true;
447       }
448       if (t >= producerTicket()) {
449         return false;
450       }
451       asm_volatile_pause();
452     }
453   }
454
455   /** findSegment */
456   FOLLY_ALWAYS_INLINE
457   Segment* findSegment(Segment* s, const Ticket t) const noexcept {
458     while (UNLIKELY(t >= (s->minTicket() + SegmentSize))) {
459       auto deadline = std::chrono::steady_clock::time_point::max();
460       s = tryGetNextSegmentUntil(s, deadline);
461       DCHECK(s != nullptr);
462     }
463     return s;
464   }
465
466   /** tryGetNextSegmentUntil */
467   template <typename Clock, typename Duration>
468   Segment* tryGetNextSegmentUntil(
469       Segment* s,
470       const std::chrono::time_point<Clock, Duration>& deadline) const noexcept {
471     // The following loop will not spin indefinitely (as long as the
472     // number of concurrently waiting consumers does not exceeds
473     // SegmentSize and the OS scheduler does not pause ready threads
474     // indefinitely). Under such conditions, the algorithm guarantees
475     // that the producer reponsible for advancing the tail pointer to
476     // the next segment has already acquired its ticket.
477     while (tail() == s) {
478       if (deadline < Clock::time_point::max() && deadline > Clock::now()) {
479         return nullptr;
480       }
481       asm_volatile_pause();
482     }
483     Segment* next = s->nextSegment();
484     DCHECK(next != nullptr);
485     return next;
486   }
487
488   /** allocNextSegment */
489   void allocNextSegment(Segment* s, const Ticket t) {
490     Segment* next = new Segment(t);
491     if (!SPSC) {
492       next->acquire_ref_safe(); // hazptr
493     }
494     DCHECK(s->nextSegment() == nullptr);
495     s->setNextSegment(next);
496   }
497
498   /** advanceTail */
499   void advanceTail(Segment* s) noexcept {
500     Segment* next = s->nextSegment();
501     if (!SingleProducer) {
502       // The following loop will not spin indefinitely (as long as the
503       // OS scheduler does not pause ready threads indefinitely). The
504       // algorithm guarantees that the producer reponsible for setting
505       // the next pointer has already acquired its ticket.
506       while (next == nullptr) {
507         asm_volatile_pause();
508         next = s->nextSegment();
509       }
510     }
511     DCHECK(next != nullptr);
512     setTail(next);
513   }
514
515   /** advanceHead */
516   void advanceHead(Segment* s) noexcept {
517     auto deadline = std::chrono::steady_clock::time_point::max();
518     Segment* next = tryGetNextSegmentUntil(s, deadline);
519     DCHECK(next != nullptr);
520     while (head() != s) {
521       // Wait for head to advance to the current segment first before
522       // advancing head to the next segment. Otherwise, a lagging
523       // consumer responsible for advancing head from an earlier
524       // segment may incorrectly set head back.
525       asm_volatile_pause();
526     }
527     setHead(next);
528     reclaimSegment(s);
529   }
530
531   /** reclaimSegment */
532   void reclaimSegment(Segment* s) noexcept {
533     if (SPSC) {
534       delete s;
535     } else {
536       s->retire(); // hazptr
537     }
538   }
539
540   FOLLY_ALWAYS_INLINE size_t index(Ticket t) const noexcept {
541     return (t * Stride) & (SegmentSize - 1);
542   }
543
544   FOLLY_ALWAYS_INLINE bool responsibleForAlloc(Ticket t) const noexcept {
545     return (t & (SegmentSize - 1)) == 0;
546   }
547
548   FOLLY_ALWAYS_INLINE bool responsibleForAdvance(Ticket t) const noexcept {
549     return (t & (SegmentSize - 1)) == (SegmentSize - 1);
550   }
551
552   FOLLY_ALWAYS_INLINE Segment* head() const noexcept {
553     return c_.head.load(std::memory_order_acquire);
554   }
555
556   FOLLY_ALWAYS_INLINE Segment* tail() const noexcept {
557     return p_.tail.load(std::memory_order_acquire);
558   }
559
560   FOLLY_ALWAYS_INLINE Ticket producerTicket() const noexcept {
561     return p_.ticket.load(std::memory_order_acquire);
562   }
563
564   FOLLY_ALWAYS_INLINE Ticket consumerTicket() const noexcept {
565     return c_.ticket.load(std::memory_order_acquire);
566   }
567
568   void setHead(Segment* s) noexcept {
569     c_.head.store(s, std::memory_order_release);
570   }
571
572   void setTail(Segment* s) noexcept {
573     p_.tail.store(s, std::memory_order_release);
574   }
575
576   FOLLY_ALWAYS_INLINE void setProducerTicket(Ticket t) noexcept {
577     p_.ticket.store(t, std::memory_order_release);
578   }
579
580   FOLLY_ALWAYS_INLINE void setConsumerTicket(Ticket t) noexcept {
581     c_.ticket.store(t, std::memory_order_release);
582   }
583
584   FOLLY_ALWAYS_INLINE Ticket fetchIncrementConsumerTicket() noexcept {
585     if (SingleConsumer) {
586       Ticket oldval = consumerTicket();
587       setConsumerTicket(oldval + 1);
588       return oldval;
589     } else { // MC
590       return c_.ticket.fetch_add(1, std::memory_order_acq_rel);
591     }
592   }
593
594   FOLLY_ALWAYS_INLINE Ticket fetchIncrementProducerTicket() noexcept {
595     if (SingleProducer) {
596       Ticket oldval = producerTicket();
597       setProducerTicket(oldval + 1);
598       return oldval;
599     } else { // MP
600       return p_.ticket.fetch_add(1, std::memory_order_acq_rel);
601     }
602   }
603
604   /**
605    *  Entry
606    */
607   class Entry {
608     folly::SaturatingSemaphore<MayBlock, Atom> flag_;
609     typename std::aligned_storage<sizeof(T), alignof(T)>::type item_;
610
611    public:
612     template <typename Arg>
613     FOLLY_ALWAYS_INLINE void putItem(Arg&& arg) {
614       new (&item_) T(std::forward<Arg>(arg));
615       flag_.post();
616     }
617
618     FOLLY_ALWAYS_INLINE void takeItem(T& item) noexcept {
619       flag_.wait();
620       getItem(item);
621     }
622
623     template <typename Clock, typename Duration>
624     FOLLY_ALWAYS_INLINE bool tryWaitUntil(
625         const std::chrono::time_point<Clock, Duration>& deadline) noexcept {
626       // wait-options from benchmarks on contended queues:
627       auto const opt =
628           flag_.wait_options().spin_max(std::chrono::microseconds(10));
629       return flag_.try_wait_until(deadline, opt);
630     }
631
632    private:
633     FOLLY_ALWAYS_INLINE void getItem(T& item) noexcept {
634       item = std::move(*(itemPtr()));
635       destroyItem();
636     }
637
638     FOLLY_ALWAYS_INLINE T* itemPtr() noexcept {
639       return static_cast<T*>(static_cast<void*>(&item_));
640     }
641
642     FOLLY_ALWAYS_INLINE void destroyItem() noexcept {
643       itemPtr()->~T();
644     }
645   }; // Entry
646
647   /**
648    *  Segment
649    */
650   class Segment : public folly::hazptr::hazptr_obj_base_refcounted<Segment> {
651     Atom<Segment*> next_;
652     const Ticket min_;
653     bool marked_; // used for iterative deletion
654     alignas(Align) Entry b_[SegmentSize];
655
656    public:
657     explicit Segment(const Ticket t)
658         : next_(nullptr), min_(t), marked_(false) {}
659
660     ~Segment() {
661       if (!SPSC && !marked_) {
662         Segment* next = nextSegment();
663         while (next) {
664           if (!next->release_ref()) { // hazptr
665             return;
666           }
667           Segment* s = next;
668           next = s->nextSegment();
669           s->marked_ = true;
670           delete s;
671         }
672       }
673     }
674
675     Segment* nextSegment() const noexcept {
676       return next_.load(std::memory_order_acquire);
677     }
678
679     void setNextSegment(Segment* s) noexcept {
680       next_.store(s, std::memory_order_release);
681     }
682
683     FOLLY_ALWAYS_INLINE Ticket minTicket() const noexcept {
684       DCHECK_EQ((min_ & (SegmentSize - 1)), 0);
685       return min_;
686     }
687
688     FOLLY_ALWAYS_INLINE Entry& entry(size_t index) noexcept {
689       return b_[index];
690     }
691   }; // Segment
692
693 }; // UnboundedQueue
694
695 /* Aliases */
696
697 template <
698     typename T,
699     bool MayBlock,
700     size_t LgSegmentSize = 8,
701     size_t LgAlign = 7,
702     template <typename> class Atom = std::atomic>
703 using USPSCQueue =
704     UnboundedQueue<T, true, true, MayBlock, LgSegmentSize, LgAlign, Atom>;
705
706 template <
707     typename T,
708     bool MayBlock,
709     size_t LgSegmentSize = 8,
710     size_t LgAlign = 7,
711     template <typename> class Atom = std::atomic>
712 using UMPSCQueue =
713     UnboundedQueue<T, false, true, MayBlock, LgSegmentSize, LgAlign, Atom>;
714
715 template <
716     typename T,
717     bool MayBlock,
718     size_t LgSegmentSize = 8,
719     size_t LgAlign = 7,
720     template <typename> class Atom = std::atomic>
721 using USPMCQueue =
722     UnboundedQueue<T, true, false, MayBlock, LgSegmentSize, LgAlign, Atom>;
723
724 template <
725     typename T,
726     bool MayBlock,
727     size_t LgSegmentSize = 8,
728     size_t LgAlign = 7,
729     template <typename> class Atom = std::atomic>
730 using UMPMCQueue =
731     UnboundedQueue<T, false, false, MayBlock, LgSegmentSize, LgAlign, Atom>;
732
733 } // namespace folly