UnboundedQueue: Fix advanceHead
[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 ryDequeueUntilMC(s, item, deadline);
381     }
382   }
383
384   /** ryDequeueUntilSC */
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 (!e.tryWaitUntil(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 ryDequeueUntilMC(
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 (!e.tryWaitUntil(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   /** findSegment */
439   FOLLY_ALWAYS_INLINE
440   Segment* findSegment(Segment* s, const Ticket t) const noexcept {
441     while (UNLIKELY(t >= (s->minTicket() + SegmentSize))) {
442       auto deadline = std::chrono::steady_clock::time_point::max();
443       s = tryGetNextSegmentUntil(s, deadline);
444       DCHECK(s != nullptr);
445     }
446     return s;
447   }
448
449   /** tryGetNextSegmentUntil */
450   template <typename Clock, typename Duration>
451   Segment* tryGetNextSegmentUntil(
452       Segment* s,
453       const std::chrono::time_point<Clock, Duration>& deadline) const noexcept {
454     // The following loop will not spin indefinitely (as long as the
455     // number of concurrently waiting consumers does not exceeds
456     // SegmentSize and the OS scheduler does not pause ready threads
457     // indefinitely). Under such conditions, the algorithm guarantees
458     // that the producer reponsible for advancing the tail pointer to
459     // the next segment has already acquired its ticket.
460     while (tail() == s) {
461       if (deadline < Clock::time_point::max() && deadline > Clock::now()) {
462         return nullptr;
463       }
464       asm_volatile_pause();
465     }
466     Segment* next = s->nextSegment();
467     DCHECK(next != nullptr);
468     return next;
469   }
470
471   /** allocNextSegment */
472   void allocNextSegment(Segment* s, const Ticket t) {
473     Segment* next = new Segment(t);
474     if (!SPSC) {
475       next->acquire_ref_safe(); // hazptr
476     }
477     DCHECK(s->nextSegment() == nullptr);
478     s->setNextSegment(next);
479   }
480
481   /** advanceTail */
482   void advanceTail(Segment* s) noexcept {
483     Segment* next = s->nextSegment();
484     if (!SingleProducer) {
485       // The following loop will not spin indefinitely (as long as the
486       // OS scheduler does not pause ready threads indefinitely). The
487       // algorithm guarantees that the producer reponsible for setting
488       // the next pointer has already acquired its ticket.
489       while (next == nullptr) {
490         asm_volatile_pause();
491         next = s->nextSegment();
492       }
493     }
494     DCHECK(next != nullptr);
495     setTail(next);
496   }
497
498   /** advanceHead */
499   void advanceHead(Segment* s) noexcept {
500     auto deadline = std::chrono::steady_clock::time_point::max();
501     Segment* next = tryGetNextSegmentUntil(s, deadline);
502     DCHECK(next != nullptr);
503     while (head() != s) {
504       // Wait for head to advance to the current segment first before
505       // advancing head to the next segment. Otherwise, a lagging
506       // consumer responsible for advancing head from an earlier
507       // segment may incorrectly set head back.
508       asm_volatile_pause();
509     }
510     setHead(next);
511     reclaimSegment(s);
512   }
513
514   /** reclaimSegment */
515   void reclaimSegment(Segment* s) noexcept {
516     if (SPSC) {
517       delete s;
518     } else {
519       s->retire(); // hazptr
520     }
521   }
522
523   FOLLY_ALWAYS_INLINE size_t index(Ticket t) const noexcept {
524     return (t * Stride) & (SegmentSize - 1);
525   }
526
527   FOLLY_ALWAYS_INLINE bool responsibleForAlloc(Ticket t) const noexcept {
528     return (t & (SegmentSize - 1)) == 0;
529   }
530
531   FOLLY_ALWAYS_INLINE bool responsibleForAdvance(Ticket t) const noexcept {
532     return (t & (SegmentSize - 1)) == (SegmentSize - 1);
533   }
534
535   FOLLY_ALWAYS_INLINE Segment* head() const noexcept {
536     return c_.head.load(std::memory_order_acquire);
537   }
538
539   FOLLY_ALWAYS_INLINE Segment* tail() const noexcept {
540     return p_.tail.load(std::memory_order_acquire);
541   }
542
543   FOLLY_ALWAYS_INLINE Ticket producerTicket() const noexcept {
544     return p_.ticket.load(std::memory_order_acquire);
545   }
546
547   FOLLY_ALWAYS_INLINE Ticket consumerTicket() const noexcept {
548     return c_.ticket.load(std::memory_order_acquire);
549   }
550
551   void setHead(Segment* s) noexcept {
552     c_.head.store(s, std::memory_order_release);
553   }
554
555   void setTail(Segment* s) noexcept {
556     p_.tail.store(s, std::memory_order_release);
557   }
558
559   FOLLY_ALWAYS_INLINE void setProducerTicket(Ticket t) noexcept {
560     p_.ticket.store(t, std::memory_order_release);
561   }
562
563   FOLLY_ALWAYS_INLINE void setConsumerTicket(Ticket t) noexcept {
564     c_.ticket.store(t, std::memory_order_release);
565   }
566
567   FOLLY_ALWAYS_INLINE Ticket fetchIncrementConsumerTicket() noexcept {
568     if (SingleConsumer) {
569       Ticket oldval = consumerTicket();
570       setConsumerTicket(oldval + 1);
571       return oldval;
572     } else { // MC
573       return c_.ticket.fetch_add(1, std::memory_order_acq_rel);
574     }
575   }
576
577   FOLLY_ALWAYS_INLINE Ticket fetchIncrementProducerTicket() noexcept {
578     if (SingleProducer) {
579       Ticket oldval = producerTicket();
580       setProducerTicket(oldval + 1);
581       return oldval;
582     } else { // MP
583       return p_.ticket.fetch_add(1, std::memory_order_acq_rel);
584     }
585   }
586
587   /**
588    *  Entry
589    */
590   class Entry {
591     folly::SaturatingSemaphore<MayBlock, Atom> flag_;
592     typename std::aligned_storage<sizeof(T), alignof(T)>::type item_;
593
594    public:
595     template <typename Arg>
596     FOLLY_ALWAYS_INLINE void putItem(Arg&& arg) {
597       new (&item_) T(std::forward<Arg>(arg));
598       flag_.post();
599     }
600
601     FOLLY_ALWAYS_INLINE void takeItem(T& item) noexcept {
602       flag_.wait();
603       getItem(item);
604     }
605
606     template <typename Clock, typename Duration>
607     FOLLY_ALWAYS_INLINE bool tryWaitUntil(
608         const std::chrono::time_point<Clock, Duration>& deadline) noexcept {
609       return flag_.try_wait_until(deadline);
610     }
611
612    private:
613     FOLLY_ALWAYS_INLINE void getItem(T& item) noexcept {
614       item = std::move(*(itemPtr()));
615       destroyItem();
616     }
617
618     FOLLY_ALWAYS_INLINE T* itemPtr() noexcept {
619       return static_cast<T*>(static_cast<void*>(&item_));
620     }
621
622     FOLLY_ALWAYS_INLINE void destroyItem() noexcept {
623       itemPtr()->~T();
624     }
625   }; // Entry
626
627   /**
628    *  Segment
629    */
630   class Segment : public folly::hazptr::hazptr_obj_base_refcounted<Segment> {
631     Atom<Segment*> next_;
632     const Ticket min_;
633     bool marked_; // used for iterative deletion
634     FOLLY_ALIGNED(Align)
635     Entry b_[SegmentSize];
636
637    public:
638     explicit Segment(const Ticket t)
639         : next_(nullptr), min_(t), marked_(false) {}
640
641     ~Segment() {
642       if (!SPSC && !marked_) {
643         Segment* next = nextSegment();
644         while (next) {
645           if (!next->release_ref()) { // hazptr
646             return;
647           }
648           Segment* s = next;
649           next = s->nextSegment();
650           s->marked_ = true;
651           delete s;
652         }
653       }
654     }
655
656     Segment* nextSegment() const noexcept {
657       return next_.load(std::memory_order_acquire);
658     }
659
660     void setNextSegment(Segment* s) noexcept {
661       next_.store(s, std::memory_order_release);
662     }
663
664     FOLLY_ALWAYS_INLINE Ticket minTicket() const noexcept {
665       DCHECK_EQ((min_ & (SegmentSize - 1)), 0);
666       return min_;
667     }
668
669     FOLLY_ALWAYS_INLINE Entry& entry(size_t index) noexcept {
670       return b_[index];
671     }
672   }; // Segment
673
674 }; // UnboundedQueue
675
676 /* Aliases */
677
678 template <
679     typename T,
680     bool MayBlock,
681     size_t LgSegmentSize = 8,
682     size_t LgAlign = 7,
683     template <typename> class Atom = std::atomic>
684 using USPSCQueue =
685     UnboundedQueue<T, true, true, MayBlock, LgSegmentSize, LgAlign, Atom>;
686
687 template <
688     typename T,
689     bool MayBlock,
690     size_t LgSegmentSize = 8,
691     size_t LgAlign = 7,
692     template <typename> class Atom = std::atomic>
693 using UMPSCQueue =
694     UnboundedQueue<T, false, true, MayBlock, LgSegmentSize, LgAlign, Atom>;
695
696 template <
697     typename T,
698     bool MayBlock,
699     size_t LgSegmentSize = 8,
700     size_t LgAlign = 7,
701     template <typename> class Atom = std::atomic>
702 using USPMCQueue =
703     UnboundedQueue<T, true, false, MayBlock, LgSegmentSize, LgAlign, Atom>;
704
705 template <
706     typename T,
707     bool MayBlock,
708     size_t LgSegmentSize = 8,
709     size_t LgAlign = 7,
710     template <typename> class Atom = std::atomic>
711 using UMPMCQueue =
712     UnboundedQueue<T, false, false, MayBlock, LgSegmentSize, LgAlign, Atom>;
713
714 } // namespace folly