2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
22 #include <boost/noncopyable.hpp>
25 #include <type_traits>
27 #include <folly/Traits.h>
28 #include <folly/detail/CacheLocality.h>
29 #include <folly/detail/TurnSequencer.h>
30 #include <folly/portability/Unistd.h>
36 template<typename T, template<typename> class Atom>
37 struct SingleElementQueue;
39 template <typename T> class MPMCPipelineStageImpl;
41 /// MPMCQueue base CRTP template
42 template <typename> class MPMCQueueBase;
46 /// MPMCQueue<T> is a high-performance bounded concurrent queue that
47 /// supports multiple producers, multiple consumers, and optional blocking.
48 /// The queue has a fixed capacity, for which all memory will be allocated
49 /// up front. The bulk of the work of enqueuing and dequeuing can be
50 /// performed in parallel.
52 /// MPMCQueue is linearizable. That means that if a call to write(A)
53 /// returns before a call to write(B) begins, then A will definitely end up
54 /// in the queue before B, and if a call to read(X) returns before a call
55 /// to read(Y) is started, that X will be something from earlier in the
56 /// queue than Y. This also means that if a read call returns a value, you
57 /// can be sure that all previous elements of the queue have been assigned
58 /// a reader (that reader might not yet have returned, but it exists).
60 /// The underlying implementation uses a ticket dispenser for the head and
61 /// the tail, spreading accesses across N single-element queues to produce
62 /// a queue with capacity N. The ticket dispensers use atomic increment,
63 /// which is more robust to contention than a CAS loop. Each of the
64 /// single-element queues uses its own CAS to serialize access, with an
65 /// adaptive spin cutoff. When spinning fails on a single-element queue
66 /// it uses futex()'s _BITSET operations to reduce unnecessary wakeups
67 /// even if multiple waiters are present on an individual queue (such as
68 /// when the MPMCQueue's capacity is smaller than the number of enqueuers
71 /// In benchmarks (contained in tao/queues/ConcurrentQueueTests)
72 /// it handles 1 to 1, 1 to N, N to 1, and N to M thread counts better
73 /// than any of the alternatives present in fbcode, for both small (~10)
74 /// and large capacities. In these benchmarks it is also faster than
75 /// tbb::concurrent_bounded_queue for all configurations. When there are
76 /// many more threads than cores, MPMCQueue is _much_ faster than the tbb
77 /// queue because it uses futex() to block and unblock waiting threads,
78 /// rather than spinning with sched_yield.
80 /// NOEXCEPT INTERACTION: tl;dr; If it compiles you're fine. Ticket-based
81 /// queues separate the assignment of queue positions from the actual
82 /// construction of the in-queue elements, which means that the T
83 /// constructor used during enqueue must not throw an exception. This is
84 /// enforced at compile time using type traits, which requires that T be
85 /// adorned with accurate noexcept information. If your type does not
86 /// use noexcept, you will have to wrap it in something that provides
87 /// the guarantee. We provide an alternate safe implementation for types
88 /// that don't use noexcept but that are marked folly::IsRelocatable
89 /// and boost::has_nothrow_constructor, which is common for folly types.
90 /// In particular, if you can declare FOLLY_ASSUME_FBVECTOR_COMPATIBLE
91 /// then your type can be put in MPMCQueue.
93 /// If you have a pool of N queue consumers that you want to shut down
94 /// after the queue has drained, one way is to enqueue N sentinel values
95 /// to the queue. If the producer doesn't know how many consumers there
96 /// are you can enqueue one sentinel and then have each consumer requeue
97 /// two sentinels after it receives it (by requeuing 2 the shutdown can
98 /// complete in O(log P) time instead of O(P)).
99 template<typename T, template<typename> class Atom = std::atomic,
100 bool Dynamic = false>
101 class MPMCQueue : public detail::MPMCQueueBase<MPMCQueue<T,Atom,Dynamic>> {
102 friend class detail::MPMCPipelineStageImpl<T>;
103 using Slot = detail::SingleElementQueue<T,Atom>;
106 explicit MPMCQueue(size_t queueCapacity)
107 : detail::MPMCQueueBase<MPMCQueue<T,Atom,Dynamic>>(queueCapacity)
109 this->stride_ = this->computeStride(queueCapacity);
110 this->slots_ = new Slot[queueCapacity + 2 * this->kSlotPadding];
113 MPMCQueue() noexcept { }
116 /// The dynamic version of MPMCQueue allows dynamic expansion of queue
117 /// capacity, such that a queue may start with a smaller capacity than
118 /// specified and expand only if needed. Users may optionally specify
119 /// the initial capacity and the expansion multiplier.
121 /// The design uses a seqlock to enforce mutual exclusion among
122 /// expansion attempts. Regular operations read up-to-date queue
123 /// information (slots array, capacity, stride) inside read-only
124 /// seqlock sections, which are unimpeded when no expansion is in
127 /// An expansion computes a new capacity, allocates a new slots array,
128 /// and updates stride. No information needs to be copied from the
129 /// current slots array to the new one. When this happens, new slots
130 /// will not have sequence numbers that match ticket numbers. The
131 /// expansion needs to compute a ticket offset such that operations
132 /// that use new arrays can adjust the calculations of slot indexes
133 /// and sequence numbers that take into account that the new slots
134 /// start with sequence numbers of zero. The current ticket offset is
135 /// packed with the seqlock in an atomic 64-bit integer. The initial
138 /// Lagging write and read operations with tickets lower than the
139 /// ticket offset of the current slots array (i.e., the minimum ticket
140 /// number that can be served by the current array) must use earlier
141 /// closed arrays instead of the current one. Information about closed
142 /// slots arrays (array address, capacity, stride, and offset) is
143 /// maintained in a logarithmic-sized structure. Each entry in that
144 /// structure never need to be changed once set. The number of closed
145 /// arrays is half the value of the seqlock (when unlocked).
147 /// The acquisition of the seqlock to perform an expansion does not
148 /// prevent the issuing of new push and pop tickets concurrently. The
149 /// expansion must set the new ticket offset to a value that couldn't
150 /// have been issued to an operation that has already gone through a
151 /// seqlock read-only section (and hence obtained information for
152 /// older closed arrays).
154 /// Note that the total queue capacity can temporarily exceed the
155 /// specified capacity when there are lagging consumers that haven't
156 /// yet consumed all the elements in closed arrays. Users should not
157 /// rely on the capacity of dynamic queues for synchronization, e.g.,
158 /// they should not expect that a thread will definitely block on a
159 /// call to blockingWrite() when the queue size is known to be equal
162 /// The dynamic version is a partial specialization of MPMCQueue with
164 template <typename T, template<typename> class Atom>
165 class MPMCQueue<T,Atom,true> :
166 public detail::MPMCQueueBase<MPMCQueue<T,Atom,true>> {
167 friend class detail::MPMCQueueBase<MPMCQueue<T,Atom,true>>;
168 using Slot = detail::SingleElementQueue<T,Atom>;
171 uint64_t offset_ {0};
172 Slot* slots_ {nullptr};
173 size_t capacity_ {0};
179 explicit MPMCQueue(size_t queueCapacity)
180 : detail::MPMCQueueBase<MPMCQueue<T,Atom,true>>(queueCapacity)
182 size_t cap = std::min<size_t>(kDefaultMinDynamicCapacity, queueCapacity);
183 initQueue(cap, kDefaultExpansionMultiplier);
186 explicit MPMCQueue(size_t queueCapacity,
188 size_t expansionMultiplier)
189 : detail::MPMCQueueBase<MPMCQueue<T,Atom,true>>(queueCapacity)
191 minCapacity = std::max<size_t>(1, minCapacity);
192 size_t cap = std::min<size_t>(minCapacity, queueCapacity);
193 expansionMultiplier = std::max<size_t>(2, expansionMultiplier);
194 initQueue(cap, expansionMultiplier);
197 MPMCQueue() noexcept {
202 MPMCQueue(MPMCQueue<T,Atom,true>&& rhs) noexcept {
203 this->capacity_ = rhs.capacity_;
204 this->slots_ = rhs.slots_;
205 this->stride_ = rhs.stride_;
206 this->dstate_.store(rhs.dstate_.load(std::memory_order_relaxed),
207 std::memory_order_relaxed);
208 this->dcapacity_.store(rhs.dcapacity_.load(std::memory_order_relaxed),
209 std::memory_order_relaxed);
210 this->pushTicket_.store(rhs.pushTicket_.load(std::memory_order_relaxed),
211 std::memory_order_relaxed);
212 this->popTicket_.store(rhs.popTicket_.load(std::memory_order_relaxed),
213 std::memory_order_relaxed);
214 this->pushSpinCutoff_.store(
215 rhs.pushSpinCutoff_.load(std::memory_order_relaxed),
216 std::memory_order_relaxed);
217 this->popSpinCutoff_.store(
218 rhs.popSpinCutoff_.load(std::memory_order_relaxed),
219 std::memory_order_relaxed);
221 closed_ = rhs.closed_;
224 rhs.slots_ = nullptr;
226 rhs.dstate_.store(0, std::memory_order_relaxed);
227 rhs.dcapacity_.store(0, std::memory_order_relaxed);
228 rhs.pushTicket_.store(0, std::memory_order_relaxed);
229 rhs.popTicket_.store(0, std::memory_order_relaxed);
230 rhs.pushSpinCutoff_.store(0, std::memory_order_relaxed);
231 rhs.popSpinCutoff_.store(0, std::memory_order_relaxed);
233 rhs.closed_ = nullptr;
236 MPMCQueue<T,Atom, true> const& operator= (MPMCQueue<T,Atom, true>&& rhs) {
239 new (this) MPMCQueue(std::move(rhs));
245 if (closed_ != nullptr) {
246 for (int i = getNumClosed(this->dstate_.load()) - 1; i >= 0; --i) {
247 delete[] closed_[i].slots_;
253 size_t allocatedCapacity() const noexcept {
254 return this->dcapacity_.load(std::memory_order_relaxed);
257 template <typename ...Args>
258 void blockingWrite(Args&&... args) noexcept {
259 uint64_t ticket = this->pushTicket_++;
266 if (!trySeqlockReadSection(state, slots, cap, stride)) {
269 if (maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride)) {
270 // There was an expansion after this ticket was issued.
273 if (slots[this->idx((ticket-offset), cap, stride)]
274 .mayEnqueue(this->turn(ticket-offset, cap))) {
275 // A slot is ready. No need to expand.
277 } else if (this->popTicket_.load(std::memory_order_relaxed) + cap
279 // May block, but a pop is in progress. No need to expand.
280 // Get seqlock read section info again in case an expansion
281 // occurred with an equal or higher ticket.
284 // May block. See if we can expand.
285 if (tryExpand(state, cap)) {
286 // This or another thread started an expansion. Get updated info.
294 this->enqueueWithTicketBase(ticket-offset, slots, cap, stride,
295 std::forward<Args>(args)...);
298 void blockingReadWithTicket(uint64_t& ticket, T& elem) noexcept {
299 ticket = this->popTicket_++;
305 while (!trySeqlockReadSection(state, slots, cap, stride));
306 // If there was an expansion after the corresponding push ticket
307 // was issued, adjust accordingly
308 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
309 this->dequeueWithTicketBase(ticket-offset, slots, cap, stride, elem);
316 kDefaultMinDynamicCapacity = 10,
317 kDefaultExpansionMultiplier = 10,
322 // Info about closed slots arrays for use by lagging operations
323 ClosedArray* closed_;
325 void initQueue(const size_t cap, const size_t mult) {
326 this->stride_ = this->computeStride(cap);
327 this->slots_ = new Slot[cap + 2 * this->kSlotPadding];
328 this->dstate_.store(0);
329 this->dcapacity_.store(cap);
331 size_t maxClosed = 0;
332 for (size_t expanded = cap;
333 expanded < this->capacity_;
337 closed_ = (maxClosed > 0) ? new ClosedArray[maxClosed] : nullptr;
340 bool tryObtainReadyPushTicket(
341 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
345 ticket = this->pushTicket_.load(std::memory_order_acquire); // A
346 if (!trySeqlockReadSection(state, slots, cap, stride)) {
350 // If there was an expansion with offset greater than this ticket,
351 // adjust accordingly
353 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
355 if (slots[this->idx((ticket-offset), cap, stride)]
356 .mayEnqueue(this->turn(ticket-offset, cap))) {
358 if (this->pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
366 if (ticket != this->pushTicket_.load(std::memory_order_relaxed)) { // B
367 // Try again. Ticket changed.
371 // Try to expand unless the ticket is for a closed array
372 if (offset == getOffset(state)) {
373 if (tryExpand(state, cap)) {
374 // This or another thread started an expansion. Get up-to-date info.
383 bool tryObtainPromisedPushTicket(
384 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
388 ticket = this->pushTicket_.load(std::memory_order_acquire);
389 auto numPops = this->popTicket_.load(std::memory_order_acquire);
390 if (!trySeqlockReadSection(state, slots, cap, stride)) {
394 const auto oldCap = cap;
395 // If there was an expansion with offset greater than this ticket,
396 // adjust accordingly
398 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
400 int64_t n = ticket - numPops;
401 if (n >= static_cast<ssize_t>(this->capacity_)) {
406 if (n >= static_cast<ssize_t>(oldCap)) {
407 if (tryExpand(state, oldCap)) {
408 // This or another thread started an expansion. Start over
418 if (this->pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
426 bool tryObtainReadyPopTicket(
427 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
431 ticket = this->popTicket_.load(std::memory_order_relaxed);
432 if (!trySeqlockReadSection(state, slots, cap, stride)) {
436 // If there was an expansion after the corresponding push ticket
437 // was issued, adjust accordingly
439 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
441 if (slots[this->idx((ticket-offset), cap, stride)]
442 .mayDequeue(this->turn(ticket-offset, cap))) {
443 if (this->popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
454 bool tryObtainPromisedPopTicket(
455 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
459 ticket = this->popTicket_.load(std::memory_order_acquire);
460 auto numPushes = this->pushTicket_.load(std::memory_order_acquire);
461 if (!trySeqlockReadSection(state, slots, cap, stride)) {
466 // If there was an expansion after the corresponding push
467 // ticket was issued, adjust accordingly
468 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
470 if (ticket >= numPushes) {
474 if (this->popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
481 /// Enqueues an element with a specific ticket number
482 template <typename ...Args>
483 void enqueueWithTicket(const uint64_t ticket, Args&&... args) noexcept {
490 while (!trySeqlockReadSection(state, slots, cap, stride)) {}
492 // If there was an expansion after this ticket was issued, adjust
494 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
496 this->enqueueWithTicketBase(ticket-offset, slots, cap, stride,
497 std::forward<Args>(args)...);
500 uint64_t getOffset(const uint64_t state) const noexcept {
501 return state >> kSeqlockBits;
504 int getNumClosed(const uint64_t state) const noexcept {
505 return (state & ((1 << kSeqlockBits) - 1)) >> 1;
508 /// Try to expand the queue. Returns true if this expansion was
509 /// successful or a concurent expansion is in progress. Returns
510 /// false if the queue has reached its maximum capacity or
511 /// allocation has failed.
512 bool tryExpand(const uint64_t state, const size_t cap) noexcept {
513 if (cap == this->capacity_) {
517 uint64_t oldval = state;
518 assert((state & 1) == 0);
519 if (this->dstate_.compare_exchange_strong(oldval, state + 1)) {
520 assert(cap == this->dcapacity_.load());
521 uint64_t ticket = 1 + std::max(this->pushTicket_.load(),
522 this->popTicket_.load());
524 std::min(dmult_ * cap, this->capacity_);
526 new (std::nothrow) Slot[newCapacity + 2 * this->kSlotPadding];
527 if (newSlots == nullptr) {
528 // Expansion failed. Restore the seqlock
529 this->dstate_.store(state);
532 // Successful expansion
533 // calculate the current ticket offset
534 uint64_t offset = getOffset(state);
535 // calculate index in closed array
536 int index = getNumClosed(state);
537 assert((index << 1) < (1 << kSeqlockBits));
538 // fill the info for the closed slots array
539 closed_[index].offset_ = offset;
540 closed_[index].slots_ = this->dslots_.load();
541 closed_[index].capacity_ = cap;
542 closed_[index].stride_ = this->dstride_.load();
543 // update the new slots array info
544 this->dslots_.store(newSlots);
545 this->dcapacity_.store(newCapacity);
546 this->dstride_.store(this->computeStride(newCapacity));
547 // Release the seqlock and record the new ticket offset
548 this->dstate_.store((ticket << kSeqlockBits) + (2 * (index + 1)));
550 } else { // failed to acquire seqlock
551 // Someone acaquired the seqlock. Go back to the caller and get
557 /// Seqlock read-only section
558 bool trySeqlockReadSection(
559 uint64_t& state, Slot*& slots, size_t& cap, int& stride
561 state = this->dstate_.load(std::memory_order_acquire);
566 // Start read-only section.
567 slots = this->dslots_.load(std::memory_order_relaxed);
568 cap = this->dcapacity_.load(std::memory_order_relaxed);
569 stride = this->dstride_.load(std::memory_order_relaxed);
570 // End of read-only section. Validate seqlock.
571 std::atomic_thread_fence(std::memory_order_acquire);
572 return (state == this->dstate_.load(std::memory_order_relaxed));
575 /// If there was an expansion after ticket was issued, update local variables
576 /// of the lagging operation using the most recent closed array with
577 /// offset <= ticket and return true. Otherwise, return false;
578 bool maybeUpdateFromClosed(
579 const uint64_t state,
580 const uint64_t ticket,
584 int& stride) noexcept {
585 offset = getOffset(state);
586 if (ticket >= offset) {
589 for (int i = getNumClosed(state) - 1; i >= 0; --i) {
590 offset = closed_[i].offset_;
591 if (offset <= ticket) {
592 slots = closed_[i].slots_;
593 cap = closed_[i].capacity_;
594 stride = closed_[i].stride_;
598 // A closed array with offset <= ticket should have been found
606 /// CRTP specialization of MPMCQueueBase
609 typename T, template<typename> class Atom, bool Dynamic> class Derived,
610 typename T, template<typename> class Atom, bool Dynamic>
611 class MPMCQueueBase<Derived<T, Atom, Dynamic>> : boost::noncopyable {
613 // Note: Using CRTP static casts in several functions of this base
614 // template instead of making called functions virtual or duplicating
615 // the code of calling functions in the derived partially specialized
618 static_assert(std::is_nothrow_constructible<T,T&&>::value ||
619 folly::IsRelocatable<T>::value,
620 "T must be relocatable or have a noexcept move constructor");
623 typedef T value_type;
625 using Slot = detail::SingleElementQueue<T,Atom>;
627 explicit MPMCQueueBase(size_t queueCapacity)
628 : capacity_(queueCapacity)
634 if (queueCapacity == 0) {
635 throw std::invalid_argument(
636 "MPMCQueue with explicit capacity 0 is impossible"
637 // Stride computation in derived classes would sigfpe if capacity is 0
641 // ideally this would be a static assert, but g++ doesn't allow it
642 assert(alignof(MPMCQueue<T,Atom>)
643 >= detail::CacheLocality::kFalseSharingRange);
644 assert(static_cast<uint8_t*>(static_cast<void*>(&popTicket_))
645 - static_cast<uint8_t*>(static_cast<void*>(&pushTicket_))
646 >= detail::CacheLocality::kFalseSharingRange);
649 /// A default-constructed queue is useful because a usable (non-zero
650 /// capacity) queue can be moved onto it or swapped with it
651 MPMCQueueBase() noexcept
663 /// IMPORTANT: The move constructor is here to make it easier to perform
664 /// the initialization phase, it is not safe to use when there are any
665 /// concurrent accesses (this is not checked).
666 MPMCQueueBase(MPMCQueueBase<Derived<T,Atom,Dynamic>>&& rhs) noexcept
667 : capacity_(rhs.capacity_)
669 , stride_(rhs.stride_)
670 , dstate_(rhs.dstate_.load(std::memory_order_relaxed))
671 , dcapacity_(rhs.dcapacity_.load(std::memory_order_relaxed))
672 , pushTicket_(rhs.pushTicket_.load(std::memory_order_relaxed))
673 , popTicket_(rhs.popTicket_.load(std::memory_order_relaxed))
674 , pushSpinCutoff_(rhs.pushSpinCutoff_.load(std::memory_order_relaxed))
675 , popSpinCutoff_(rhs.popSpinCutoff_.load(std::memory_order_relaxed))
677 // relaxed ops are okay for the previous reads, since rhs queue can't
678 // be in concurrent use
682 rhs.slots_ = nullptr;
684 rhs.dstate_.store(0, std::memory_order_relaxed);
685 rhs.dcapacity_.store(0, std::memory_order_relaxed);
686 rhs.pushTicket_.store(0, std::memory_order_relaxed);
687 rhs.popTicket_.store(0, std::memory_order_relaxed);
688 rhs.pushSpinCutoff_.store(0, std::memory_order_relaxed);
689 rhs.popSpinCutoff_.store(0, std::memory_order_relaxed);
692 /// IMPORTANT: The move operator is here to make it easier to perform
693 /// the initialization phase, it is not safe to use when there are any
694 /// concurrent accesses (this is not checked).
695 MPMCQueueBase<Derived<T,Atom,Dynamic>> const& operator=
696 (MPMCQueueBase<Derived<T,Atom,Dynamic>>&& rhs) {
698 this->~MPMCQueueBase();
699 new (this) MPMCQueueBase(std::move(rhs));
704 /// MPMCQueue can only be safely destroyed when there are no
705 /// pending enqueuers or dequeuers (this is not checked).
710 /// Returns the number of writes (including threads that are blocked waiting
711 /// to write) minus the number of reads (including threads that are blocked
712 /// waiting to read). So effectively, it becomes:
713 /// elements in queue + pending(calls to write) - pending(calls to read).
714 /// If nothing is pending, then the method returns the actual number of
715 /// elements in the queue.
716 /// The returned value can be negative if there are no writers and the queue
717 /// is empty, but there is one reader that is blocked waiting to read (in
718 /// which case, the returned size will be -1).
719 ssize_t size() const noexcept {
720 // since both pushes and pops increase monotonically, we can get a
721 // consistent snapshot either by bracketing a read of popTicket_ with
722 // two reads of pushTicket_ that return the same value, or the other
723 // way around. We maximize our chances by alternately attempting
725 uint64_t pushes = pushTicket_.load(std::memory_order_acquire); // A
726 uint64_t pops = popTicket_.load(std::memory_order_acquire); // B
728 uint64_t nextPushes = pushTicket_.load(std::memory_order_acquire); // C
729 if (pushes == nextPushes) {
730 // pushTicket_ didn't change from A (or the previous C) to C,
731 // so we can linearize at B (or D)
732 return pushes - pops;
735 uint64_t nextPops = popTicket_.load(std::memory_order_acquire); // D
736 if (pops == nextPops) {
737 // popTicket_ didn't chance from B (or the previous D), so we
738 // can linearize at C
739 return pushes - pops;
745 /// Returns true if there are no items available for dequeue
746 bool isEmpty() const noexcept {
750 /// Returns true if there is currently no empty space to enqueue
751 bool isFull() const noexcept {
752 // careful with signed -> unsigned promotion, since size can be negative
753 return size() >= static_cast<ssize_t>(capacity_);
756 /// Returns is a guess at size() for contexts that don't need a precise
757 /// value, such as stats. More specifically, it returns the number of writes
758 /// minus the number of reads, but after reading the number of writes, more
759 /// writers could have came before the number of reads was sampled,
760 /// and this method doesn't protect against such case.
761 /// The returned value can be negative.
762 ssize_t sizeGuess() const noexcept {
763 return writeCount() - readCount();
767 size_t capacity() const noexcept {
771 /// Doesn't change for non-dynamic
772 size_t allocatedCapacity() const noexcept {
776 /// Returns the total number of calls to blockingWrite or successful
777 /// calls to write, including those blockingWrite calls that are
778 /// currently blocking
779 uint64_t writeCount() const noexcept {
780 return pushTicket_.load(std::memory_order_acquire);
783 /// Returns the total number of calls to blockingRead or successful
784 /// calls to read, including those blockingRead calls that are currently
786 uint64_t readCount() const noexcept {
787 return popTicket_.load(std::memory_order_acquire);
790 /// Enqueues a T constructed from args, blocking until space is
791 /// available. Note that this method signature allows enqueue via
792 /// move, if args is a T rvalue, via copy, if args is a T lvalue, or
793 /// via emplacement if args is an initializer list that can be passed
794 /// to a T constructor.
795 template <typename ...Args>
796 void blockingWrite(Args&&... args) noexcept {
797 enqueueWithTicketBase(pushTicket_++, slots_, capacity_, stride_,
798 std::forward<Args>(args)...);
801 /// If an item can be enqueued with no blocking, does so and returns
802 /// true, otherwise returns false. This method is similar to
803 /// writeIfNotFull, but if you don't have a specific need for that
804 /// method you should use this one.
806 /// One of the common usages of this method is to enqueue via the
807 /// move constructor, something like q.write(std::move(x)). If write
808 /// returns false because the queue is full then x has not actually been
809 /// consumed, which looks strange. To understand why it is actually okay
810 /// to use x afterward, remember that std::move is just a typecast that
811 /// provides an rvalue reference that enables use of a move constructor
812 /// or operator. std::move doesn't actually move anything. It could
813 /// more accurately be called std::rvalue_cast or std::move_permission.
814 template <typename ...Args>
815 bool write(Args&&... args) noexcept {
820 if (static_cast<Derived<T,Atom,Dynamic>*>(this)->
821 tryObtainReadyPushTicket(ticket, slots, cap, stride)) {
822 // we have pre-validated that the ticket won't block
823 enqueueWithTicketBase(ticket, slots, cap, stride,
824 std::forward<Args>(args)...);
831 template <class Clock, typename... Args>
832 bool tryWriteUntil(const std::chrono::time_point<Clock>& when,
833 Args&&... args) noexcept {
838 if (tryObtainPromisedPushTicketUntil(ticket, slots, cap, stride, when)) {
839 // we have pre-validated that the ticket won't block, or rather that
840 // it won't block longer than it takes another thread to dequeue an
841 // element from the slot it identifies.
842 enqueueWithTicketBase(ticket, slots, cap, stride,
843 std::forward<Args>(args)...);
850 /// If the queue is not full, enqueues and returns true, otherwise
851 /// returns false. Unlike write this method can be blocked by another
852 /// thread, specifically a read that has linearized (been assigned
853 /// a ticket) but not yet completed. If you don't really need this
854 /// function you should probably use write.
856 /// MPMCQueue isn't lock-free, so just because a read operation has
857 /// linearized (and isFull is false) doesn't mean that space has been
858 /// made available for another write. In this situation write will
859 /// return false, but writeIfNotFull will wait for the dequeue to finish.
860 /// This method is required if you are composing queues and managing
861 /// your own wakeup, because it guarantees that after every successful
862 /// write a readIfNotEmpty will succeed.
863 template <typename ...Args>
864 bool writeIfNotFull(Args&&... args) noexcept {
869 if (static_cast<Derived<T,Atom,Dynamic>*>(this)->
870 tryObtainPromisedPushTicket(ticket, slots, cap, stride)) {
871 // some other thread is already dequeuing the slot into which we
872 // are going to enqueue, but we might have to wait for them to finish
873 enqueueWithTicketBase(ticket, slots, cap, stride,
874 std::forward<Args>(args)...);
881 /// Moves a dequeued element onto elem, blocking until an element
883 void blockingRead(T& elem) noexcept {
885 static_cast<Derived<T,Atom,Dynamic>*>(this)->
886 blockingReadWithTicket(ticket, elem);
889 /// Same as blockingRead() but also records the ticket nunmer
890 void blockingReadWithTicket(uint64_t& ticket, T& elem) noexcept {
891 assert(capacity_ != 0);
892 ticket = popTicket_++;
893 dequeueWithTicketBase(ticket, slots_, capacity_, stride_, elem);
896 /// If an item can be dequeued with no blocking, does so and returns
897 /// true, otherwise returns false.
898 bool read(T& elem) noexcept {
900 return readAndGetTicket(ticket, elem);
903 /// Same as read() but also records the ticket nunmer
904 bool readAndGetTicket(uint64_t& ticket, T& elem) noexcept {
908 if (static_cast<Derived<T,Atom,Dynamic>*>(this)->
909 tryObtainReadyPopTicket(ticket, slots, cap, stride)) {
910 // the ticket has been pre-validated to not block
911 dequeueWithTicketBase(ticket, slots, cap, stride, elem);
918 template <class Clock, typename... Args>
920 const std::chrono::time_point<Clock>& when,
926 if (tryObtainPromisedPopTicketUntil(ticket, slots, cap, stride, when)) {
927 // we have pre-validated that the ticket won't block, or rather that
928 // it won't block longer than it takes another thread to enqueue an
929 // element on the slot it identifies.
930 dequeueWithTicketBase(ticket, slots, cap, stride, elem);
937 /// If the queue is not empty, dequeues and returns true, otherwise
938 /// returns false. If the matching write is still in progress then this
939 /// method may block waiting for it. If you don't rely on being able
940 /// to dequeue (such as by counting completed write) then you should
942 bool readIfNotEmpty(T& elem) noexcept {
947 if (static_cast<Derived<T,Atom,Dynamic>*>(this)->
948 tryObtainPromisedPopTicket(ticket, slots, cap, stride)) {
949 // the matching enqueue already has a ticket, but might not be done
950 dequeueWithTicketBase(ticket, slots, cap, stride, elem);
959 /// Once every kAdaptationFreq we will spin longer, to try to estimate
960 /// the proper spin backoff
961 kAdaptationFreq = 128,
963 /// To avoid false sharing in slots_ with neighboring memory
964 /// allocations, we pad it with this many SingleElementQueue-s at
966 kSlotPadding = (detail::CacheLocality::kFalseSharingRange - 1)
970 /// The maximum number of items in the queue at once
971 size_t FOLLY_ALIGN_TO_AVOID_FALSE_SHARING capacity_;
973 /// Anonymous union for use when Dynamic = false and true, respectively
975 /// An array of capacity_ SingleElementQueue-s, each of which holds
976 /// either 0 or 1 item. We over-allocate by 2 * kSlotPadding and don't
977 /// touch the slots at either end, to avoid false sharing
979 /// Current dynamic slots array of dcapacity_ SingleElementQueue-s
983 /// Anonymous union for use when Dynamic = false and true, respectively
985 /// The number of slots_ indices that we advance for each ticket, to
986 /// avoid false sharing. Ideally slots_[i] and slots_[i + stride_]
987 /// aren't on the same cache line
993 /// The following two memebers are used by dynamic MPMCQueue.
994 /// Ideally they should be in MPMCQueue<T,Atom,true>, but we get
995 /// better cache locality if they are in the same cache line as
996 /// dslots_ and dstride_.
998 /// Dynamic state. A packed seqlock and ticket offset
999 Atom<uint64_t> dstate_;
1000 /// Dynamic capacity
1001 Atom<size_t> dcapacity_;
1003 /// Enqueuers get tickets from here
1004 Atom<uint64_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING pushTicket_;
1006 /// Dequeuers get tickets from here
1007 Atom<uint64_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING popTicket_;
1009 /// This is how many times we will spin before using FUTEX_WAIT when
1010 /// the queue is full on enqueue, adaptively computed by occasionally
1011 /// spinning for longer and smoothing with an exponential moving average
1012 Atom<uint32_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING pushSpinCutoff_;
1014 /// The adaptive spin cutoff when the queue is empty on dequeue
1015 Atom<uint32_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING popSpinCutoff_;
1017 /// Alignment doesn't prevent false sharing at the end of the struct,
1018 /// so fill out the last cache line
1019 char padding_[detail::CacheLocality::kFalseSharingRange -
1020 sizeof(Atom<uint32_t>)];
1022 /// We assign tickets in increasing order, but we don't want to
1023 /// access neighboring elements of slots_ because that will lead to
1024 /// false sharing (multiple cores accessing the same cache line even
1025 /// though they aren't accessing the same bytes in that cache line).
1026 /// To avoid this we advance by stride slots per ticket.
1028 /// We need gcd(capacity, stride) to be 1 so that we will use all
1029 /// of the slots. We ensure this by only considering prime strides,
1030 /// which either have no common divisors with capacity or else have
1031 /// a zero remainder after dividing by capacity. That is sufficient
1032 /// to guarantee correctness, but we also want to actually spread the
1033 /// accesses away from each other to avoid false sharing (consider a
1034 /// stride of 7 with a capacity of 8). To that end we try a few taking
1035 /// care to observe that advancing by -1 is as bad as advancing by 1
1036 /// when in comes to false sharing.
1038 /// The simple way to avoid false sharing would be to pad each
1039 /// SingleElementQueue, but since we have capacity_ of them that could
1040 /// waste a lot of space.
1041 static int computeStride(size_t capacity) noexcept {
1042 static const int smallPrimes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };
1046 for (int stride : smallPrimes) {
1047 if ((stride % capacity) == 0 || (capacity % stride) == 0) {
1050 size_t sep = stride % capacity;
1051 sep = std::min(sep, capacity - sep);
1052 if (sep > bestSep) {
1053 bestStride = stride;
1060 /// Returns the index into slots_ that should be used when enqueuing or
1061 /// dequeuing with the specified ticket
1062 size_t idx(uint64_t ticket, size_t cap, int stride) noexcept {
1063 return ((ticket * stride) % cap) + kSlotPadding;
1066 /// Maps an enqueue or dequeue ticket to the turn should be used at the
1067 /// corresponding SingleElementQueue
1068 uint32_t turn(uint64_t ticket, size_t cap) noexcept {
1070 return ticket / cap;
1073 /// Tries to obtain a push ticket for which SingleElementQueue::enqueue
1074 /// won't block. Returns true on immediate success, false on immediate
1076 bool tryObtainReadyPushTicket(
1077 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
1079 ticket = pushTicket_.load(std::memory_order_acquire); // A
1084 if (!slots[idx(ticket, cap, stride)]
1085 .mayEnqueue(turn(ticket, cap))) {
1086 // if we call enqueue(ticket, ...) on the SingleElementQueue
1087 // right now it would block, but this might no longer be the next
1088 // ticket. We can increase the chance of tryEnqueue success under
1089 // contention (without blocking) by rechecking the ticket dispenser
1091 ticket = pushTicket_.load(std::memory_order_acquire); // B
1092 if (prev == ticket) {
1093 // mayEnqueue was bracketed by two reads (A or prev B or prev
1094 // failing CAS to B), so we are definitely unable to enqueue
1098 // we will bracket the mayEnqueue check with a read (A or prev B
1099 // or prev failing CAS) and the following CAS. If the CAS fails
1100 // it will effect a load of pushTicket_
1101 if (pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
1108 /// Tries until when to obtain a push ticket for which
1109 /// SingleElementQueue::enqueue won't block. Returns true on success, false
1111 /// ticket is filled on success AND failure.
1112 template <class Clock>
1113 bool tryObtainPromisedPushTicketUntil(
1114 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride,
1115 const std::chrono::time_point<Clock>& when
1117 bool deadlineReached = false;
1118 while (!deadlineReached) {
1119 if (static_cast<Derived<T,Atom,Dynamic>*>(this)->
1120 tryObtainPromisedPushTicket(ticket, slots, cap, stride)) {
1123 // ticket is a blocking ticket until the preceding ticket has been
1124 // processed: wait until this ticket's turn arrives. We have not reserved
1125 // this ticket so we will have to re-attempt to get a non-blocking ticket
1126 // if we wake up before we time-out.
1127 deadlineReached = !slots[idx(ticket, cap, stride)]
1128 .tryWaitForEnqueueTurnUntil(turn(ticket, cap), pushSpinCutoff_,
1129 (ticket % kAdaptationFreq) == 0, when);
1134 /// Tries to obtain a push ticket which can be satisfied if all
1135 /// in-progress pops complete. This function does not block, but
1136 /// blocking may be required when using the returned ticket if some
1137 /// other thread's pop is still in progress (ticket has been granted but
1138 /// pop has not yet completed).
1139 bool tryObtainPromisedPushTicket(
1140 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
1142 auto numPushes = pushTicket_.load(std::memory_order_acquire); // A
1148 const auto numPops = popTicket_.load(std::memory_order_acquire); // B
1149 // n will be negative if pops are pending
1150 const int64_t n = numPushes - numPops;
1151 if (n >= static_cast<ssize_t>(capacity_)) {
1152 // Full, linearize at B. We don't need to recheck the read we
1153 // performed at A, because if numPushes was stale at B then the
1154 // real numPushes value is even worse
1157 if (pushTicket_.compare_exchange_strong(numPushes, numPushes + 1)) {
1163 /// Tries to obtain a pop ticket for which SingleElementQueue::dequeue
1164 /// won't block. Returns true on immediate success, false on immediate
1166 bool tryObtainReadyPopTicket(
1167 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
1169 ticket = popTicket_.load(std::memory_order_acquire);
1174 if (!slots[idx(ticket, cap, stride)]
1175 .mayDequeue(turn(ticket, cap))) {
1177 ticket = popTicket_.load(std::memory_order_acquire);
1178 if (prev == ticket) {
1182 if (popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
1189 /// Tries until when to obtain a pop ticket for which
1190 /// SingleElementQueue::dequeue won't block. Returns true on success, false
1192 /// ticket is filled on success AND failure.
1193 template <class Clock>
1194 bool tryObtainPromisedPopTicketUntil(
1199 const std::chrono::time_point<Clock>& when) noexcept {
1200 bool deadlineReached = false;
1201 while (!deadlineReached) {
1202 if (static_cast<Derived<T, Atom, Dynamic>*>(this)
1203 ->tryObtainPromisedPopTicket(ticket, slots, cap, stride)) {
1206 // ticket is a blocking ticket until the preceding ticket has been
1207 // processed: wait until this ticket's turn arrives. We have not reserved
1208 // this ticket so we will have to re-attempt to get a non-blocking ticket
1209 // if we wake up before we time-out.
1211 !slots[idx(ticket, cap, stride)].tryWaitForDequeueTurnUntil(
1214 (ticket % kAdaptationFreq) == 0,
1220 /// Similar to tryObtainReadyPopTicket, but returns a pop ticket whose
1221 /// corresponding push ticket has already been handed out, rather than
1222 /// returning one whose corresponding push ticket has already been
1223 /// completed. This means that there is a possibility that the caller
1224 /// will block when using the ticket, but it allows the user to rely on
1225 /// the fact that if enqueue has succeeded, tryObtainPromisedPopTicket
1226 /// will return true. The "try" part of this is that we won't have
1227 /// to block waiting for someone to call enqueue, although we might
1228 /// have to block waiting for them to finish executing code inside the
1229 /// MPMCQueue itself.
1230 bool tryObtainPromisedPopTicket(
1231 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
1233 auto numPops = popTicket_.load(std::memory_order_acquire); // A
1239 const auto numPushes = pushTicket_.load(std::memory_order_acquire); // B
1240 if (numPops >= numPushes) {
1241 // Empty, or empty with pending pops. Linearize at B. We don't
1242 // need to recheck the read we performed at A, because if numPops
1243 // is stale then the fresh value is larger and the >= is still true
1246 if (popTicket_.compare_exchange_strong(numPops, numPops + 1)) {
1252 // Given a ticket, constructs an enqueued item using args
1253 template <typename ...Args>
1254 void enqueueWithTicketBase(
1255 uint64_t ticket, Slot* slots, size_t cap, int stride, Args&&... args
1257 slots[idx(ticket, cap, stride)]
1258 .enqueue(turn(ticket, cap),
1260 (ticket % kAdaptationFreq) == 0,
1261 std::forward<Args>(args)...);
1264 // To support tracking ticket numbers in MPMCPipelineStageImpl
1265 template <typename ...Args>
1266 void enqueueWithTicket(uint64_t ticket, Args&&... args) noexcept {
1267 enqueueWithTicketBase(ticket, slots_, capacity_, stride_,
1268 std::forward<Args>(args)...);
1271 // Given a ticket, dequeues the corresponding element
1272 void dequeueWithTicketBase(
1273 uint64_t ticket, Slot* slots, size_t cap, int stride, T& elem
1276 slots[idx(ticket, cap, stride)]
1277 .dequeue(turn(ticket, cap),
1279 (ticket % kAdaptationFreq) == 0,
1284 /// SingleElementQueue implements a blocking queue that holds at most one
1285 /// item, and that requires its users to assign incrementing identifiers
1286 /// (turns) to each enqueue and dequeue operation. Note that the turns
1287 /// used by SingleElementQueue are doubled inside the TurnSequencer
1288 template <typename T, template <typename> class Atom>
1289 struct SingleElementQueue {
1291 ~SingleElementQueue() noexcept {
1292 if ((sequencer_.uncompletedTurnLSB() & 1) == 1) {
1293 // we are pending a dequeue, so we have a constructed item
1298 /// enqueue using in-place noexcept construction
1299 template <typename ...Args,
1300 typename = typename std::enable_if<
1301 std::is_nothrow_constructible<T,Args...>::value>::type>
1302 void enqueue(const uint32_t turn,
1303 Atom<uint32_t>& spinCutoff,
1304 const bool updateSpinCutoff,
1305 Args&&... args) noexcept {
1306 sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
1307 new (&contents_) T(std::forward<Args>(args)...);
1308 sequencer_.completeTurn(turn * 2);
1311 /// enqueue using move construction, either real (if
1312 /// is_nothrow_move_constructible) or simulated using relocation and
1313 /// default construction (if IsRelocatable and has_nothrow_constructor)
1314 template <typename = typename std::enable_if<
1315 (folly::IsRelocatable<T>::value &&
1316 boost::has_nothrow_constructor<T>::value) ||
1317 std::is_nothrow_constructible<T, T&&>::value>::type>
1318 void enqueue(const uint32_t turn,
1319 Atom<uint32_t>& spinCutoff,
1320 const bool updateSpinCutoff,
1321 T&& goner) noexcept {
1327 typename std::conditional<std::is_nothrow_constructible<T,T&&>::value,
1328 ImplByMove, ImplByRelocation>::type());
1331 /// Waits until either:
1332 /// 1: the dequeue turn preceding the given enqueue turn has arrived
1333 /// 2: the given deadline has arrived
1334 /// Case 1 returns true, case 2 returns false.
1335 template <class Clock>
1336 bool tryWaitForEnqueueTurnUntil(
1337 const uint32_t turn,
1338 Atom<uint32_t>& spinCutoff,
1339 const bool updateSpinCutoff,
1340 const std::chrono::time_point<Clock>& when) noexcept {
1341 return sequencer_.tryWaitForTurn(
1342 turn * 2, spinCutoff, updateSpinCutoff, &when) !=
1343 TurnSequencer<Atom>::TryWaitResult::TIMEDOUT;
1346 bool mayEnqueue(const uint32_t turn) const noexcept {
1347 return sequencer_.isTurn(turn * 2);
1350 void dequeue(uint32_t turn,
1351 Atom<uint32_t>& spinCutoff,
1352 const bool updateSpinCutoff,
1358 typename std::conditional<folly::IsRelocatable<T>::value,
1360 ImplByMove>::type());
1363 /// Waits until either:
1364 /// 1: the enqueue turn preceding the given dequeue turn has arrived
1365 /// 2: the given deadline has arrived
1366 /// Case 1 returns true, case 2 returns false.
1367 template <class Clock>
1368 bool tryWaitForDequeueTurnUntil(
1369 const uint32_t turn,
1370 Atom<uint32_t>& spinCutoff,
1371 const bool updateSpinCutoff,
1372 const std::chrono::time_point<Clock>& when) noexcept {
1373 return sequencer_.tryWaitForTurn(
1374 turn * 2 + 1, spinCutoff, updateSpinCutoff, &when) !=
1375 TurnSequencer<Atom>::TryWaitResult::TIMEDOUT;
1378 bool mayDequeue(const uint32_t turn) const noexcept {
1379 return sequencer_.isTurn(turn * 2 + 1);
1383 /// Storage for a T constructed with placement new
1384 typename std::aligned_storage<sizeof(T),alignof(T)>::type contents_;
1386 /// Even turns are pushes, odd turns are pops
1387 TurnSequencer<Atom> sequencer_;
1390 return static_cast<T*>(static_cast<void*>(&contents_));
1393 void destroyContents() noexcept {
1397 // g++ doesn't seem to have std::is_nothrow_destructible yet
1400 memset(&contents_, 'Q', sizeof(T));
1404 /// Tag classes for dispatching to enqueue/dequeue implementation.
1405 struct ImplByRelocation {};
1406 struct ImplByMove {};
1408 /// enqueue using nothrow move construction.
1409 void enqueueImpl(const uint32_t turn,
1410 Atom<uint32_t>& spinCutoff,
1411 const bool updateSpinCutoff,
1413 ImplByMove) noexcept {
1414 sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
1415 new (&contents_) T(std::move(goner));
1416 sequencer_.completeTurn(turn * 2);
1419 /// enqueue by simulating nothrow move with relocation, followed by
1420 /// default construction to a noexcept relocation.
1421 void enqueueImpl(const uint32_t turn,
1422 Atom<uint32_t>& spinCutoff,
1423 const bool updateSpinCutoff,
1425 ImplByRelocation) noexcept {
1426 sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
1427 memcpy(&contents_, &goner, sizeof(T));
1428 sequencer_.completeTurn(turn * 2);
1432 /// dequeue by destructing followed by relocation. This version is preferred,
1433 /// because as much work as possible can be done before waiting.
1434 void dequeueImpl(uint32_t turn,
1435 Atom<uint32_t>& spinCutoff,
1436 const bool updateSpinCutoff,
1438 ImplByRelocation) noexcept {
1442 // unlikely, but if we don't complete our turn the queue will die
1444 sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
1445 memcpy(&elem, &contents_, sizeof(T));
1446 sequencer_.completeTurn(turn * 2 + 1);
1449 /// dequeue by nothrow move assignment.
1450 void dequeueImpl(uint32_t turn,
1451 Atom<uint32_t>& spinCutoff,
1452 const bool updateSpinCutoff,
1454 ImplByMove) noexcept {
1455 sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
1456 elem = std::move(*ptr());
1458 sequencer_.completeTurn(turn * 2 + 1);
1462 } // namespace detail
1464 } // namespace folly