2 * Copyright 2017 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.
24 #include <type_traits>
26 #include <boost/noncopyable.hpp>
28 #include <folly/Traits.h>
29 #include <folly/concurrency/CacheLocality.h>
30 #include <folly/detail/TurnSequencer.h>
31 #include <folly/portability/Unistd.h>
37 template <typename T, template <typename> class Atom>
38 struct SingleElementQueue;
40 template <typename T> class MPMCPipelineStageImpl;
42 /// MPMCQueue base CRTP template
43 template <typename> class MPMCQueueBase;
47 /// MPMCQueue<T> is a high-performance bounded concurrent queue that
48 /// supports multiple producers, multiple consumers, and optional blocking.
49 /// The queue has a fixed capacity, for which all memory will be allocated
50 /// up front. The bulk of the work of enqueuing and dequeuing can be
51 /// performed in parallel.
53 /// MPMCQueue is linearizable. That means that if a call to write(A)
54 /// returns before a call to write(B) begins, then A will definitely end up
55 /// in the queue before B, and if a call to read(X) returns before a call
56 /// to read(Y) is started, that X will be something from earlier in the
57 /// queue than Y. This also means that if a read call returns a value, you
58 /// can be sure that all previous elements of the queue have been assigned
59 /// a reader (that reader might not yet have returned, but it exists).
61 /// The underlying implementation uses a ticket dispenser for the head and
62 /// the tail, spreading accesses across N single-element queues to produce
63 /// a queue with capacity N. The ticket dispensers use atomic increment,
64 /// which is more robust to contention than a CAS loop. Each of the
65 /// single-element queues uses its own CAS to serialize access, with an
66 /// adaptive spin cutoff. When spinning fails on a single-element queue
67 /// it uses futex()'s _BITSET operations to reduce unnecessary wakeups
68 /// even if multiple waiters are present on an individual queue (such as
69 /// when the MPMCQueue's capacity is smaller than the number of enqueuers
72 /// In benchmarks (contained in tao/queues/ConcurrentQueueTests)
73 /// it handles 1 to 1, 1 to N, N to 1, and N to M thread counts better
74 /// than any of the alternatives present in fbcode, for both small (~10)
75 /// and large capacities. In these benchmarks it is also faster than
76 /// tbb::concurrent_bounded_queue for all configurations. When there are
77 /// many more threads than cores, MPMCQueue is _much_ faster than the tbb
78 /// queue because it uses futex() to block and unblock waiting threads,
79 /// rather than spinning with sched_yield.
81 /// NOEXCEPT INTERACTION: tl;dr; If it compiles you're fine. Ticket-based
82 /// queues separate the assignment of queue positions from the actual
83 /// construction of the in-queue elements, which means that the T
84 /// constructor used during enqueue must not throw an exception. This is
85 /// enforced at compile time using type traits, which requires that T be
86 /// adorned with accurate noexcept information. If your type does not
87 /// use noexcept, you will have to wrap it in something that provides
88 /// the guarantee. We provide an alternate safe implementation for types
89 /// that don't use noexcept but that are marked folly::IsRelocatable
90 /// and std::is_nothrow_constructible, which is common for folly types.
91 /// In particular, if you can declare FOLLY_ASSUME_FBVECTOR_COMPATIBLE
92 /// then your type can be put in MPMCQueue.
94 /// If you have a pool of N queue consumers that you want to shut down
95 /// after the queue has drained, one way is to enqueue N sentinel values
96 /// to the queue. If the producer doesn't know how many consumers there
97 /// are you can enqueue one sentinel and then have each consumer requeue
98 /// two sentinels after it receives it (by requeuing 2 the shutdown can
99 /// complete in O(log P) time instead of O(P)).
102 template <typename> class Atom = std::atomic,
103 bool Dynamic = false>
104 class MPMCQueue : public detail::MPMCQueueBase<MPMCQueue<T,Atom,Dynamic>> {
105 friend class detail::MPMCPipelineStageImpl<T>;
106 using Slot = detail::SingleElementQueue<T,Atom>;
109 explicit MPMCQueue(size_t queueCapacity)
110 : detail::MPMCQueueBase<MPMCQueue<T,Atom,Dynamic>>(queueCapacity)
112 this->stride_ = this->computeStride(queueCapacity);
113 this->slots_ = new Slot[queueCapacity + 2 * this->kSlotPadding];
116 MPMCQueue() noexcept { }
119 /// The dynamic version of MPMCQueue allows dynamic expansion of queue
120 /// capacity, such that a queue may start with a smaller capacity than
121 /// specified and expand only if needed. Users may optionally specify
122 /// the initial capacity and the expansion multiplier.
124 /// The design uses a seqlock to enforce mutual exclusion among
125 /// expansion attempts. Regular operations read up-to-date queue
126 /// information (slots array, capacity, stride) inside read-only
127 /// seqlock sections, which are unimpeded when no expansion is in
130 /// An expansion computes a new capacity, allocates a new slots array,
131 /// and updates stride. No information needs to be copied from the
132 /// current slots array to the new one. When this happens, new slots
133 /// will not have sequence numbers that match ticket numbers. The
134 /// expansion needs to compute a ticket offset such that operations
135 /// that use new arrays can adjust the calculations of slot indexes
136 /// and sequence numbers that take into account that the new slots
137 /// start with sequence numbers of zero. The current ticket offset is
138 /// packed with the seqlock in an atomic 64-bit integer. The initial
141 /// Lagging write and read operations with tickets lower than the
142 /// ticket offset of the current slots array (i.e., the minimum ticket
143 /// number that can be served by the current array) must use earlier
144 /// closed arrays instead of the current one. Information about closed
145 /// slots arrays (array address, capacity, stride, and offset) is
146 /// maintained in a logarithmic-sized structure. Each entry in that
147 /// structure never need to be changed once set. The number of closed
148 /// arrays is half the value of the seqlock (when unlocked).
150 /// The acquisition of the seqlock to perform an expansion does not
151 /// prevent the issuing of new push and pop tickets concurrently. The
152 /// expansion must set the new ticket offset to a value that couldn't
153 /// have been issued to an operation that has already gone through a
154 /// seqlock read-only section (and hence obtained information for
155 /// older closed arrays).
157 /// Note that the total queue capacity can temporarily exceed the
158 /// specified capacity when there are lagging consumers that haven't
159 /// yet consumed all the elements in closed arrays. Users should not
160 /// rely on the capacity of dynamic queues for synchronization, e.g.,
161 /// they should not expect that a thread will definitely block on a
162 /// call to blockingWrite() when the queue size is known to be equal
165 /// Note that some writeIfNotFull() and tryWriteUntil() operations may
166 /// fail even if the size of the queue is less than its maximum
167 /// capacity and despite the success of expansion, if the operation
168 /// happens to acquire a ticket that belongs to a closed array. This
169 /// is a transient condition. Typically, one or two ticket values may
170 /// be subject to such condition per expansion.
172 /// The dynamic version is a partial specialization of MPMCQueue with
174 template <typename T, template <typename> class Atom>
175 class MPMCQueue<T,Atom,true> :
176 public detail::MPMCQueueBase<MPMCQueue<T,Atom,true>> {
177 friend class detail::MPMCQueueBase<MPMCQueue<T,Atom,true>>;
178 using Slot = detail::SingleElementQueue<T,Atom>;
181 uint64_t offset_ {0};
182 Slot* slots_ {nullptr};
183 size_t capacity_ {0};
189 explicit MPMCQueue(size_t queueCapacity)
190 : detail::MPMCQueueBase<MPMCQueue<T,Atom,true>>(queueCapacity)
192 size_t cap = std::min<size_t>(kDefaultMinDynamicCapacity, queueCapacity);
193 initQueue(cap, kDefaultExpansionMultiplier);
196 explicit MPMCQueue(size_t queueCapacity,
198 size_t expansionMultiplier)
199 : detail::MPMCQueueBase<MPMCQueue<T,Atom,true>>(queueCapacity)
201 minCapacity = std::max<size_t>(1, minCapacity);
202 size_t cap = std::min<size_t>(minCapacity, queueCapacity);
203 expansionMultiplier = std::max<size_t>(2, expansionMultiplier);
204 initQueue(cap, expansionMultiplier);
207 MPMCQueue() noexcept {
212 MPMCQueue(MPMCQueue<T,Atom,true>&& rhs) noexcept {
213 this->capacity_ = rhs.capacity_;
214 this->slots_ = rhs.slots_;
215 this->stride_ = rhs.stride_;
216 this->dstate_.store(rhs.dstate_.load(std::memory_order_relaxed),
217 std::memory_order_relaxed);
218 this->dcapacity_.store(rhs.dcapacity_.load(std::memory_order_relaxed),
219 std::memory_order_relaxed);
220 this->pushTicket_.store(rhs.pushTicket_.load(std::memory_order_relaxed),
221 std::memory_order_relaxed);
222 this->popTicket_.store(rhs.popTicket_.load(std::memory_order_relaxed),
223 std::memory_order_relaxed);
224 this->pushSpinCutoff_.store(
225 rhs.pushSpinCutoff_.load(std::memory_order_relaxed),
226 std::memory_order_relaxed);
227 this->popSpinCutoff_.store(
228 rhs.popSpinCutoff_.load(std::memory_order_relaxed),
229 std::memory_order_relaxed);
231 closed_ = rhs.closed_;
234 rhs.slots_ = nullptr;
236 rhs.dstate_.store(0, std::memory_order_relaxed);
237 rhs.dcapacity_.store(0, std::memory_order_relaxed);
238 rhs.pushTicket_.store(0, std::memory_order_relaxed);
239 rhs.popTicket_.store(0, std::memory_order_relaxed);
240 rhs.pushSpinCutoff_.store(0, std::memory_order_relaxed);
241 rhs.popSpinCutoff_.store(0, std::memory_order_relaxed);
243 rhs.closed_ = nullptr;
246 MPMCQueue<T,Atom, true> const& operator= (MPMCQueue<T,Atom, true>&& rhs) {
249 new (this) MPMCQueue(std::move(rhs));
255 if (closed_ != nullptr) {
256 for (int i = getNumClosed(this->dstate_.load()) - 1; i >= 0; --i) {
257 delete[] closed_[i].slots_;
263 size_t allocatedCapacity() const noexcept {
264 return this->dcapacity_.load(std::memory_order_relaxed);
267 template <typename ...Args>
268 void blockingWrite(Args&&... args) noexcept {
269 uint64_t ticket = this->pushTicket_++;
276 if (!trySeqlockReadSection(state, slots, cap, stride)) {
277 asm_volatile_pause();
280 if (maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride)) {
281 // There was an expansion after this ticket was issued.
284 if (slots[this->idx((ticket-offset), cap, stride)]
285 .mayEnqueue(this->turn(ticket-offset, cap))) {
286 // A slot is ready. No need to expand.
288 } else if (this->popTicket_.load(std::memory_order_relaxed) + cap
290 // May block, but a pop is in progress. No need to expand.
291 // Get seqlock read section info again in case an expansion
292 // occurred with an equal or higher ticket.
295 // May block. See if we can expand.
296 if (tryExpand(state, cap)) {
297 // This or another thread started an expansion. Get updated info.
305 this->enqueueWithTicketBase(ticket-offset, slots, cap, stride,
306 std::forward<Args>(args)...);
309 void blockingReadWithTicket(uint64_t& ticket, T& elem) noexcept {
310 ticket = this->popTicket_++;
316 while (!trySeqlockReadSection(state, slots, cap, stride)) {
317 asm_volatile_pause();
319 // If there was an expansion after the corresponding push ticket
320 // was issued, adjust accordingly
321 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
322 this->dequeueWithTicketBase(ticket-offset, slots, cap, stride, elem);
329 kDefaultMinDynamicCapacity = 10,
330 kDefaultExpansionMultiplier = 10,
335 // Info about closed slots arrays for use by lagging operations
336 ClosedArray* closed_;
338 void initQueue(const size_t cap, const size_t mult) {
339 this->stride_ = this->computeStride(cap);
340 this->slots_ = new Slot[cap + 2 * this->kSlotPadding];
341 this->dstate_.store(0);
342 this->dcapacity_.store(cap);
344 size_t maxClosed = 0;
345 for (size_t expanded = cap;
346 expanded < this->capacity_;
350 closed_ = (maxClosed > 0) ? new ClosedArray[maxClosed] : nullptr;
353 bool tryObtainReadyPushTicket(
354 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
358 ticket = this->pushTicket_.load(std::memory_order_acquire); // A
359 if (!trySeqlockReadSection(state, slots, cap, stride)) {
360 asm_volatile_pause();
364 // If there was an expansion with offset greater than this ticket,
365 // adjust accordingly
367 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
369 if (slots[this->idx((ticket-offset), cap, stride)]
370 .mayEnqueue(this->turn(ticket-offset, cap))) {
372 if (this->pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
380 if (ticket != this->pushTicket_.load(std::memory_order_relaxed)) { // B
381 // Try again. Ticket changed.
385 // Try to expand unless the ticket is for a closed array
386 if (offset == getOffset(state)) {
387 if (tryExpand(state, cap)) {
388 // This or another thread started an expansion. Get up-to-date info.
397 bool tryObtainPromisedPushTicket(
398 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
402 ticket = this->pushTicket_.load(std::memory_order_acquire);
403 auto numPops = this->popTicket_.load(std::memory_order_acquire);
404 if (!trySeqlockReadSection(state, slots, cap, stride)) {
405 asm_volatile_pause();
409 const auto curCap = cap;
410 // If there was an expansion with offset greater than this ticket,
411 // adjust accordingly
413 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
415 int64_t n = ticket - numPops;
417 if (n >= static_cast<ssize_t>(cap)) {
418 if ((cap == curCap) && tryExpand(state, cap)) {
419 // This or another thread started an expansion. Start over.
427 if (this->pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
435 bool tryObtainReadyPopTicket(
436 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
440 ticket = this->popTicket_.load(std::memory_order_relaxed);
441 if (!trySeqlockReadSection(state, slots, cap, stride)) {
442 asm_volatile_pause();
446 // If there was an expansion after the corresponding push ticket
447 // was issued, adjust accordingly
449 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
451 if (slots[this->idx((ticket-offset), cap, stride)]
452 .mayDequeue(this->turn(ticket-offset, cap))) {
453 if (this->popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
464 bool tryObtainPromisedPopTicket(
465 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
469 ticket = this->popTicket_.load(std::memory_order_acquire);
470 auto numPushes = this->pushTicket_.load(std::memory_order_acquire);
471 if (!trySeqlockReadSection(state, slots, cap, stride)) {
472 asm_volatile_pause();
477 // If there was an expansion after the corresponding push
478 // ticket was issued, adjust accordingly
479 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
481 if (ticket >= numPushes) {
485 if (this->popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
492 /// Enqueues an element with a specific ticket number
493 template <typename ...Args>
494 void enqueueWithTicket(const uint64_t ticket, Args&&... args) noexcept {
501 while (!trySeqlockReadSection(state, slots, cap, stride)) {}
503 // If there was an expansion after this ticket was issued, adjust
505 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
507 this->enqueueWithTicketBase(ticket-offset, slots, cap, stride,
508 std::forward<Args>(args)...);
511 uint64_t getOffset(const uint64_t state) const noexcept {
512 return state >> kSeqlockBits;
515 int getNumClosed(const uint64_t state) const noexcept {
516 return (state & ((1 << kSeqlockBits) - 1)) >> 1;
519 /// Try to expand the queue. Returns true if this expansion was
520 /// successful or a concurent expansion is in progress. Returns
521 /// false if the queue has reached its maximum capacity or
522 /// allocation has failed.
523 bool tryExpand(const uint64_t state, const size_t cap) noexcept {
524 if (cap == this->capacity_) {
528 uint64_t oldval = state;
529 assert((state & 1) == 0);
530 if (this->dstate_.compare_exchange_strong(oldval, state + 1)) {
531 assert(cap == this->dcapacity_.load());
532 uint64_t ticket = 1 + std::max(this->pushTicket_.load(),
533 this->popTicket_.load());
535 std::min(dmult_ * cap, this->capacity_);
537 new (std::nothrow) Slot[newCapacity + 2 * this->kSlotPadding];
538 if (newSlots == nullptr) {
539 // Expansion failed. Restore the seqlock
540 this->dstate_.store(state);
543 // Successful expansion
544 // calculate the current ticket offset
545 uint64_t offset = getOffset(state);
546 // calculate index in closed array
547 int index = getNumClosed(state);
548 assert((index << 1) < (1 << kSeqlockBits));
549 // fill the info for the closed slots array
550 closed_[index].offset_ = offset;
551 closed_[index].slots_ = this->dslots_.load();
552 closed_[index].capacity_ = cap;
553 closed_[index].stride_ = this->dstride_.load();
554 // update the new slots array info
555 this->dslots_.store(newSlots);
556 this->dcapacity_.store(newCapacity);
557 this->dstride_.store(this->computeStride(newCapacity));
558 // Release the seqlock and record the new ticket offset
559 this->dstate_.store((ticket << kSeqlockBits) + (2 * (index + 1)));
561 } else { // failed to acquire seqlock
562 // Someone acaquired the seqlock. Go back to the caller and get
568 /// Seqlock read-only section
569 bool trySeqlockReadSection(
570 uint64_t& state, Slot*& slots, size_t& cap, int& stride
572 state = this->dstate_.load(std::memory_order_acquire);
577 // Start read-only section.
578 slots = this->dslots_.load(std::memory_order_relaxed);
579 cap = this->dcapacity_.load(std::memory_order_relaxed);
580 stride = this->dstride_.load(std::memory_order_relaxed);
581 // End of read-only section. Validate seqlock.
582 std::atomic_thread_fence(std::memory_order_acquire);
583 return (state == this->dstate_.load(std::memory_order_relaxed));
586 /// If there was an expansion after ticket was issued, update local variables
587 /// of the lagging operation using the most recent closed array with
588 /// offset <= ticket and return true. Otherwise, return false;
589 bool maybeUpdateFromClosed(
590 const uint64_t state,
591 const uint64_t ticket,
595 int& stride) noexcept {
596 offset = getOffset(state);
597 if (ticket >= offset) {
600 for (int i = getNumClosed(state) - 1; i >= 0; --i) {
601 offset = closed_[i].offset_;
602 if (offset <= ticket) {
603 slots = closed_[i].slots_;
604 cap = closed_[i].capacity_;
605 stride = closed_[i].stride_;
609 // A closed array with offset <= ticket should have been found
617 /// CRTP specialization of MPMCQueueBase
619 template <typename T, template <typename> class Atom, bool Dynamic>
622 template <typename> class Atom,
624 class MPMCQueueBase<Derived<T, Atom, Dynamic>> : boost::noncopyable {
626 // Note: Using CRTP static casts in several functions of this base
627 // template instead of making called functions virtual or duplicating
628 // the code of calling functions in the derived partially specialized
631 static_assert(std::is_nothrow_constructible<T,T&&>::value ||
632 folly::IsRelocatable<T>::value,
633 "T must be relocatable or have a noexcept move constructor");
636 typedef T value_type;
638 using Slot = detail::SingleElementQueue<T,Atom>;
640 explicit MPMCQueueBase(size_t queueCapacity)
641 : capacity_(queueCapacity)
647 if (queueCapacity == 0) {
648 throw std::invalid_argument(
649 "MPMCQueue with explicit capacity 0 is impossible"
650 // Stride computation in derived classes would sigfpe if capacity is 0
654 // ideally this would be a static assert, but g++ doesn't allow it
655 assert(alignof(MPMCQueue<T, Atom>) >= CacheLocality::kFalseSharingRange);
657 static_cast<uint8_t*>(static_cast<void*>(&popTicket_)) -
658 static_cast<uint8_t*>(static_cast<void*>(&pushTicket_)) >=
659 CacheLocality::kFalseSharingRange);
662 /// A default-constructed queue is useful because a usable (non-zero
663 /// capacity) queue can be moved onto it or swapped with it
664 MPMCQueueBase() noexcept
676 /// IMPORTANT: The move constructor is here to make it easier to perform
677 /// the initialization phase, it is not safe to use when there are any
678 /// concurrent accesses (this is not checked).
679 MPMCQueueBase(MPMCQueueBase<Derived<T,Atom,Dynamic>>&& rhs) noexcept
680 : capacity_(rhs.capacity_)
682 , stride_(rhs.stride_)
683 , dstate_(rhs.dstate_.load(std::memory_order_relaxed))
684 , dcapacity_(rhs.dcapacity_.load(std::memory_order_relaxed))
685 , pushTicket_(rhs.pushTicket_.load(std::memory_order_relaxed))
686 , popTicket_(rhs.popTicket_.load(std::memory_order_relaxed))
687 , pushSpinCutoff_(rhs.pushSpinCutoff_.load(std::memory_order_relaxed))
688 , popSpinCutoff_(rhs.popSpinCutoff_.load(std::memory_order_relaxed))
690 // relaxed ops are okay for the previous reads, since rhs queue can't
691 // be in concurrent use
695 rhs.slots_ = nullptr;
697 rhs.dstate_.store(0, std::memory_order_relaxed);
698 rhs.dcapacity_.store(0, std::memory_order_relaxed);
699 rhs.pushTicket_.store(0, std::memory_order_relaxed);
700 rhs.popTicket_.store(0, std::memory_order_relaxed);
701 rhs.pushSpinCutoff_.store(0, std::memory_order_relaxed);
702 rhs.popSpinCutoff_.store(0, std::memory_order_relaxed);
705 /// IMPORTANT: The move operator is here to make it easier to perform
706 /// the initialization phase, it is not safe to use when there are any
707 /// concurrent accesses (this is not checked).
708 MPMCQueueBase<Derived<T,Atom,Dynamic>> const& operator=
709 (MPMCQueueBase<Derived<T,Atom,Dynamic>>&& rhs) {
711 this->~MPMCQueueBase();
712 new (this) MPMCQueueBase(std::move(rhs));
717 /// MPMCQueue can only be safely destroyed when there are no
718 /// pending enqueuers or dequeuers (this is not checked).
723 /// Returns the number of writes (including threads that are blocked waiting
724 /// to write) minus the number of reads (including threads that are blocked
725 /// waiting to read). So effectively, it becomes:
726 /// elements in queue + pending(calls to write) - pending(calls to read).
727 /// If nothing is pending, then the method returns the actual number of
728 /// elements in the queue.
729 /// The returned value can be negative if there are no writers and the queue
730 /// is empty, but there is one reader that is blocked waiting to read (in
731 /// which case, the returned size will be -1).
732 ssize_t size() const noexcept {
733 // since both pushes and pops increase monotonically, we can get a
734 // consistent snapshot either by bracketing a read of popTicket_ with
735 // two reads of pushTicket_ that return the same value, or the other
736 // way around. We maximize our chances by alternately attempting
738 uint64_t pushes = pushTicket_.load(std::memory_order_acquire); // A
739 uint64_t pops = popTicket_.load(std::memory_order_acquire); // B
741 uint64_t nextPushes = pushTicket_.load(std::memory_order_acquire); // C
742 if (pushes == nextPushes) {
743 // pushTicket_ didn't change from A (or the previous C) to C,
744 // so we can linearize at B (or D)
745 return ssize_t(pushes - pops);
748 uint64_t nextPops = popTicket_.load(std::memory_order_acquire); // D
749 if (pops == nextPops) {
750 // popTicket_ didn't chance from B (or the previous D), so we
751 // can linearize at C
752 return ssize_t(pushes - pops);
758 /// Returns true if there are no items available for dequeue
759 bool isEmpty() const noexcept {
763 /// Returns true if there is currently no empty space to enqueue
764 bool isFull() const noexcept {
765 // careful with signed -> unsigned promotion, since size can be negative
766 return size() >= static_cast<ssize_t>(capacity_);
769 /// Returns is a guess at size() for contexts that don't need a precise
770 /// value, such as stats. More specifically, it returns the number of writes
771 /// minus the number of reads, but after reading the number of writes, more
772 /// writers could have came before the number of reads was sampled,
773 /// and this method doesn't protect against such case.
774 /// The returned value can be negative.
775 ssize_t sizeGuess() const noexcept {
776 return writeCount() - readCount();
780 size_t capacity() const noexcept {
784 /// Doesn't change for non-dynamic
785 size_t allocatedCapacity() const noexcept {
789 /// Returns the total number of calls to blockingWrite or successful
790 /// calls to write, including those blockingWrite calls that are
791 /// currently blocking
792 uint64_t writeCount() const noexcept {
793 return pushTicket_.load(std::memory_order_acquire);
796 /// Returns the total number of calls to blockingRead or successful
797 /// calls to read, including those blockingRead calls that are currently
799 uint64_t readCount() const noexcept {
800 return popTicket_.load(std::memory_order_acquire);
803 /// Enqueues a T constructed from args, blocking until space is
804 /// available. Note that this method signature allows enqueue via
805 /// move, if args is a T rvalue, via copy, if args is a T lvalue, or
806 /// via emplacement if args is an initializer list that can be passed
807 /// to a T constructor.
808 template <typename ...Args>
809 void blockingWrite(Args&&... args) noexcept {
810 enqueueWithTicketBase(pushTicket_++, slots_, capacity_, stride_,
811 std::forward<Args>(args)...);
814 /// If an item can be enqueued with no blocking, does so and returns
815 /// true, otherwise returns false. This method is similar to
816 /// writeIfNotFull, but if you don't have a specific need for that
817 /// method you should use this one.
819 /// One of the common usages of this method is to enqueue via the
820 /// move constructor, something like q.write(std::move(x)). If write
821 /// returns false because the queue is full then x has not actually been
822 /// consumed, which looks strange. To understand why it is actually okay
823 /// to use x afterward, remember that std::move is just a typecast that
824 /// provides an rvalue reference that enables use of a move constructor
825 /// or operator. std::move doesn't actually move anything. It could
826 /// more accurately be called std::rvalue_cast or std::move_permission.
827 template <typename ...Args>
828 bool write(Args&&... args) noexcept {
833 if (static_cast<Derived<T,Atom,Dynamic>*>(this)->
834 tryObtainReadyPushTicket(ticket, slots, cap, stride)) {
835 // we have pre-validated that the ticket won't block
836 enqueueWithTicketBase(ticket, slots, cap, stride,
837 std::forward<Args>(args)...);
844 template <class Clock, typename... Args>
845 bool tryWriteUntil(const std::chrono::time_point<Clock>& when,
846 Args&&... args) noexcept {
851 if (tryObtainPromisedPushTicketUntil(ticket, slots, cap, stride, when)) {
852 // we have pre-validated that the ticket won't block, or rather that
853 // it won't block longer than it takes another thread to dequeue an
854 // element from the slot it identifies.
855 enqueueWithTicketBase(ticket, slots, cap, stride,
856 std::forward<Args>(args)...);
863 /// If the queue is not full, enqueues and returns true, otherwise
864 /// returns false. Unlike write this method can be blocked by another
865 /// thread, specifically a read that has linearized (been assigned
866 /// a ticket) but not yet completed. If you don't really need this
867 /// function you should probably use write.
869 /// MPMCQueue isn't lock-free, so just because a read operation has
870 /// linearized (and isFull is false) doesn't mean that space has been
871 /// made available for another write. In this situation write will
872 /// return false, but writeIfNotFull will wait for the dequeue to finish.
873 /// This method is required if you are composing queues and managing
874 /// your own wakeup, because it guarantees that after every successful
875 /// write a readIfNotEmpty will succeed.
876 template <typename ...Args>
877 bool writeIfNotFull(Args&&... args) noexcept {
882 if (static_cast<Derived<T,Atom,Dynamic>*>(this)->
883 tryObtainPromisedPushTicket(ticket, slots, cap, stride)) {
884 // some other thread is already dequeuing the slot into which we
885 // are going to enqueue, but we might have to wait for them to finish
886 enqueueWithTicketBase(ticket, slots, cap, stride,
887 std::forward<Args>(args)...);
894 /// Moves a dequeued element onto elem, blocking until an element
896 void blockingRead(T& elem) noexcept {
898 static_cast<Derived<T,Atom,Dynamic>*>(this)->
899 blockingReadWithTicket(ticket, elem);
902 /// Same as blockingRead() but also records the ticket nunmer
903 void blockingReadWithTicket(uint64_t& ticket, T& elem) noexcept {
904 assert(capacity_ != 0);
905 ticket = popTicket_++;
906 dequeueWithTicketBase(ticket, slots_, capacity_, stride_, elem);
909 /// If an item can be dequeued with no blocking, does so and returns
910 /// true, otherwise returns false.
911 bool read(T& elem) noexcept {
913 return readAndGetTicket(ticket, elem);
916 /// Same as read() but also records the ticket nunmer
917 bool readAndGetTicket(uint64_t& ticket, T& elem) noexcept {
921 if (static_cast<Derived<T,Atom,Dynamic>*>(this)->
922 tryObtainReadyPopTicket(ticket, slots, cap, stride)) {
923 // the ticket has been pre-validated to not block
924 dequeueWithTicketBase(ticket, slots, cap, stride, elem);
931 template <class Clock, typename... Args>
933 const std::chrono::time_point<Clock>& when,
939 if (tryObtainPromisedPopTicketUntil(ticket, slots, cap, stride, when)) {
940 // we have pre-validated that the ticket won't block, or rather that
941 // it won't block longer than it takes another thread to enqueue an
942 // element on the slot it identifies.
943 dequeueWithTicketBase(ticket, slots, cap, stride, elem);
950 /// If the queue is not empty, dequeues and returns true, otherwise
951 /// returns false. If the matching write is still in progress then this
952 /// method may block waiting for it. If you don't rely on being able
953 /// to dequeue (such as by counting completed write) then you should
955 bool readIfNotEmpty(T& elem) noexcept {
960 if (static_cast<Derived<T,Atom,Dynamic>*>(this)->
961 tryObtainPromisedPopTicket(ticket, slots, cap, stride)) {
962 // the matching enqueue already has a ticket, but might not be done
963 dequeueWithTicketBase(ticket, slots, cap, stride, elem);
972 /// Once every kAdaptationFreq we will spin longer, to try to estimate
973 /// the proper spin backoff
974 kAdaptationFreq = 128,
976 /// To avoid false sharing in slots_ with neighboring memory
977 /// allocations, we pad it with this many SingleElementQueue-s at
979 kSlotPadding = (CacheLocality::kFalseSharingRange - 1) / sizeof(Slot) + 1
982 /// The maximum number of items in the queue at once
983 size_t FOLLY_ALIGN_TO_AVOID_FALSE_SHARING capacity_;
985 /// Anonymous union for use when Dynamic = false and true, respectively
987 /// An array of capacity_ SingleElementQueue-s, each of which holds
988 /// either 0 or 1 item. We over-allocate by 2 * kSlotPadding and don't
989 /// touch the slots at either end, to avoid false sharing
991 /// Current dynamic slots array of dcapacity_ SingleElementQueue-s
995 /// Anonymous union for use when Dynamic = false and true, respectively
997 /// The number of slots_ indices that we advance for each ticket, to
998 /// avoid false sharing. Ideally slots_[i] and slots_[i + stride_]
999 /// aren't on the same cache line
1005 /// The following two memebers are used by dynamic MPMCQueue.
1006 /// Ideally they should be in MPMCQueue<T,Atom,true>, but we get
1007 /// better cache locality if they are in the same cache line as
1008 /// dslots_ and dstride_.
1010 /// Dynamic state. A packed seqlock and ticket offset
1011 Atom<uint64_t> dstate_;
1012 /// Dynamic capacity
1013 Atom<size_t> dcapacity_;
1015 /// Enqueuers get tickets from here
1016 Atom<uint64_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING pushTicket_;
1018 /// Dequeuers get tickets from here
1019 Atom<uint64_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING popTicket_;
1021 /// This is how many times we will spin before using FUTEX_WAIT when
1022 /// the queue is full on enqueue, adaptively computed by occasionally
1023 /// spinning for longer and smoothing with an exponential moving average
1024 Atom<uint32_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING pushSpinCutoff_;
1026 /// The adaptive spin cutoff when the queue is empty on dequeue
1027 Atom<uint32_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING popSpinCutoff_;
1029 /// Alignment doesn't prevent false sharing at the end of the struct,
1030 /// so fill out the last cache line
1031 char padding_[CacheLocality::kFalseSharingRange - sizeof(Atom<uint32_t>)];
1033 /// We assign tickets in increasing order, but we don't want to
1034 /// access neighboring elements of slots_ because that will lead to
1035 /// false sharing (multiple cores accessing the same cache line even
1036 /// though they aren't accessing the same bytes in that cache line).
1037 /// To avoid this we advance by stride slots per ticket.
1039 /// We need gcd(capacity, stride) to be 1 so that we will use all
1040 /// of the slots. We ensure this by only considering prime strides,
1041 /// which either have no common divisors with capacity or else have
1042 /// a zero remainder after dividing by capacity. That is sufficient
1043 /// to guarantee correctness, but we also want to actually spread the
1044 /// accesses away from each other to avoid false sharing (consider a
1045 /// stride of 7 with a capacity of 8). To that end we try a few taking
1046 /// care to observe that advancing by -1 is as bad as advancing by 1
1047 /// when in comes to false sharing.
1049 /// The simple way to avoid false sharing would be to pad each
1050 /// SingleElementQueue, but since we have capacity_ of them that could
1051 /// waste a lot of space.
1052 static int computeStride(size_t capacity) noexcept {
1053 static const int smallPrimes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };
1057 for (int stride : smallPrimes) {
1058 if ((stride % capacity) == 0 || (capacity % stride) == 0) {
1061 size_t sep = stride % capacity;
1062 sep = std::min(sep, capacity - sep);
1063 if (sep > bestSep) {
1064 bestStride = stride;
1071 /// Returns the index into slots_ that should be used when enqueuing or
1072 /// dequeuing with the specified ticket
1073 size_t idx(uint64_t ticket, size_t cap, int stride) noexcept {
1074 return ((ticket * stride) % cap) + kSlotPadding;
1077 /// Maps an enqueue or dequeue ticket to the turn should be used at the
1078 /// corresponding SingleElementQueue
1079 uint32_t turn(uint64_t ticket, size_t cap) noexcept {
1081 return uint32_t(ticket / cap);
1084 /// Tries to obtain a push ticket for which SingleElementQueue::enqueue
1085 /// won't block. Returns true on immediate success, false on immediate
1087 bool tryObtainReadyPushTicket(
1088 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
1090 ticket = pushTicket_.load(std::memory_order_acquire); // A
1095 if (!slots[idx(ticket, cap, stride)]
1096 .mayEnqueue(turn(ticket, cap))) {
1097 // if we call enqueue(ticket, ...) on the SingleElementQueue
1098 // right now it would block, but this might no longer be the next
1099 // ticket. We can increase the chance of tryEnqueue success under
1100 // contention (without blocking) by rechecking the ticket dispenser
1102 ticket = pushTicket_.load(std::memory_order_acquire); // B
1103 if (prev == ticket) {
1104 // mayEnqueue was bracketed by two reads (A or prev B or prev
1105 // failing CAS to B), so we are definitely unable to enqueue
1109 // we will bracket the mayEnqueue check with a read (A or prev B
1110 // or prev failing CAS) and the following CAS. If the CAS fails
1111 // it will effect a load of pushTicket_
1112 if (pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
1119 /// Tries until when to obtain a push ticket for which
1120 /// SingleElementQueue::enqueue won't block. Returns true on success, false
1122 /// ticket is filled on success AND failure.
1123 template <class Clock>
1124 bool tryObtainPromisedPushTicketUntil(
1125 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride,
1126 const std::chrono::time_point<Clock>& when
1128 bool deadlineReached = false;
1129 while (!deadlineReached) {
1130 if (static_cast<Derived<T,Atom,Dynamic>*>(this)->
1131 tryObtainPromisedPushTicket(ticket, slots, cap, stride)) {
1134 // ticket is a blocking ticket until the preceding ticket has been
1135 // processed: wait until this ticket's turn arrives. We have not reserved
1136 // this ticket so we will have to re-attempt to get a non-blocking ticket
1137 // if we wake up before we time-out.
1138 deadlineReached = !slots[idx(ticket, cap, stride)]
1139 .tryWaitForEnqueueTurnUntil(turn(ticket, cap), pushSpinCutoff_,
1140 (ticket % kAdaptationFreq) == 0, when);
1145 /// Tries to obtain a push ticket which can be satisfied if all
1146 /// in-progress pops complete. This function does not block, but
1147 /// blocking may be required when using the returned ticket if some
1148 /// other thread's pop is still in progress (ticket has been granted but
1149 /// pop has not yet completed).
1150 bool tryObtainPromisedPushTicket(
1151 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
1153 auto numPushes = pushTicket_.load(std::memory_order_acquire); // A
1159 const auto numPops = popTicket_.load(std::memory_order_acquire); // B
1160 // n will be negative if pops are pending
1161 const int64_t n = int64_t(numPushes - numPops);
1162 if (n >= static_cast<ssize_t>(capacity_)) {
1163 // Full, linearize at B. We don't need to recheck the read we
1164 // performed at A, because if numPushes was stale at B then the
1165 // real numPushes value is even worse
1168 if (pushTicket_.compare_exchange_strong(numPushes, numPushes + 1)) {
1174 /// Tries to obtain a pop ticket for which SingleElementQueue::dequeue
1175 /// won't block. Returns true on immediate success, false on immediate
1177 bool tryObtainReadyPopTicket(
1178 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
1180 ticket = popTicket_.load(std::memory_order_acquire);
1185 if (!slots[idx(ticket, cap, stride)]
1186 .mayDequeue(turn(ticket, cap))) {
1188 ticket = popTicket_.load(std::memory_order_acquire);
1189 if (prev == ticket) {
1193 if (popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
1200 /// Tries until when to obtain a pop ticket for which
1201 /// SingleElementQueue::dequeue won't block. Returns true on success, false
1203 /// ticket is filled on success AND failure.
1204 template <class Clock>
1205 bool tryObtainPromisedPopTicketUntil(
1210 const std::chrono::time_point<Clock>& when) noexcept {
1211 bool deadlineReached = false;
1212 while (!deadlineReached) {
1213 if (static_cast<Derived<T, Atom, Dynamic>*>(this)
1214 ->tryObtainPromisedPopTicket(ticket, slots, cap, stride)) {
1217 // ticket is a blocking ticket until the preceding ticket has been
1218 // processed: wait until this ticket's turn arrives. We have not reserved
1219 // this ticket so we will have to re-attempt to get a non-blocking ticket
1220 // if we wake up before we time-out.
1222 !slots[idx(ticket, cap, stride)].tryWaitForDequeueTurnUntil(
1225 (ticket % kAdaptationFreq) == 0,
1231 /// Similar to tryObtainReadyPopTicket, but returns a pop ticket whose
1232 /// corresponding push ticket has already been handed out, rather than
1233 /// returning one whose corresponding push ticket has already been
1234 /// completed. This means that there is a possibility that the caller
1235 /// will block when using the ticket, but it allows the user to rely on
1236 /// the fact that if enqueue has succeeded, tryObtainPromisedPopTicket
1237 /// will return true. The "try" part of this is that we won't have
1238 /// to block waiting for someone to call enqueue, although we might
1239 /// have to block waiting for them to finish executing code inside the
1240 /// MPMCQueue itself.
1241 bool tryObtainPromisedPopTicket(
1242 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
1244 auto numPops = popTicket_.load(std::memory_order_acquire); // A
1250 const auto numPushes = pushTicket_.load(std::memory_order_acquire); // B
1251 if (numPops >= numPushes) {
1252 // Empty, or empty with pending pops. Linearize at B. We don't
1253 // need to recheck the read we performed at A, because if numPops
1254 // is stale then the fresh value is larger and the >= is still true
1257 if (popTicket_.compare_exchange_strong(numPops, numPops + 1)) {
1263 // Given a ticket, constructs an enqueued item using args
1264 template <typename ...Args>
1265 void enqueueWithTicketBase(
1266 uint64_t ticket, Slot* slots, size_t cap, int stride, Args&&... args
1268 slots[idx(ticket, cap, stride)]
1269 .enqueue(turn(ticket, cap),
1271 (ticket % kAdaptationFreq) == 0,
1272 std::forward<Args>(args)...);
1275 // To support tracking ticket numbers in MPMCPipelineStageImpl
1276 template <typename ...Args>
1277 void enqueueWithTicket(uint64_t ticket, Args&&... args) noexcept {
1278 enqueueWithTicketBase(ticket, slots_, capacity_, stride_,
1279 std::forward<Args>(args)...);
1282 // Given a ticket, dequeues the corresponding element
1283 void dequeueWithTicketBase(
1284 uint64_t ticket, Slot* slots, size_t cap, int stride, T& elem
1287 slots[idx(ticket, cap, stride)]
1288 .dequeue(turn(ticket, cap),
1290 (ticket % kAdaptationFreq) == 0,
1295 /// SingleElementQueue implements a blocking queue that holds at most one
1296 /// item, and that requires its users to assign incrementing identifiers
1297 /// (turns) to each enqueue and dequeue operation. Note that the turns
1298 /// used by SingleElementQueue are doubled inside the TurnSequencer
1299 template <typename T, template <typename> class Atom>
1300 struct SingleElementQueue {
1302 ~SingleElementQueue() noexcept {
1303 if ((sequencer_.uncompletedTurnLSB() & 1) == 1) {
1304 // we are pending a dequeue, so we have a constructed item
1309 /// enqueue using in-place noexcept construction
1312 typename = typename std::enable_if<
1313 std::is_nothrow_constructible<T, Args...>::value>::type>
1314 void enqueue(const uint32_t turn,
1315 Atom<uint32_t>& spinCutoff,
1316 const bool updateSpinCutoff,
1317 Args&&... args) noexcept {
1318 sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
1319 new (&contents_) T(std::forward<Args>(args)...);
1320 sequencer_.completeTurn(turn * 2);
1323 /// enqueue using move construction, either real (if
1324 /// is_nothrow_move_constructible) or simulated using relocation and
1325 /// default construction (if IsRelocatable and is_nothrow_constructible)
1327 typename = typename std::enable_if<
1328 (folly::IsRelocatable<T>::value &&
1329 std::is_nothrow_constructible<T>::value) ||
1330 std::is_nothrow_constructible<T, T&&>::value>::type>
1332 const uint32_t turn,
1333 Atom<uint32_t>& spinCutoff,
1334 const bool updateSpinCutoff,
1335 T&& goner) noexcept {
1341 typename std::conditional<std::is_nothrow_constructible<T,T&&>::value,
1342 ImplByMove, ImplByRelocation>::type());
1345 /// Waits until either:
1346 /// 1: the dequeue turn preceding the given enqueue turn has arrived
1347 /// 2: the given deadline has arrived
1348 /// Case 1 returns true, case 2 returns false.
1349 template <class Clock>
1350 bool tryWaitForEnqueueTurnUntil(
1351 const uint32_t turn,
1352 Atom<uint32_t>& spinCutoff,
1353 const bool updateSpinCutoff,
1354 const std::chrono::time_point<Clock>& when) noexcept {
1355 return sequencer_.tryWaitForTurn(
1356 turn * 2, spinCutoff, updateSpinCutoff, &when) !=
1357 TurnSequencer<Atom>::TryWaitResult::TIMEDOUT;
1360 bool mayEnqueue(const uint32_t turn) const noexcept {
1361 return sequencer_.isTurn(turn * 2);
1364 void dequeue(uint32_t turn,
1365 Atom<uint32_t>& spinCutoff,
1366 const bool updateSpinCutoff,
1372 typename std::conditional<folly::IsRelocatable<T>::value,
1374 ImplByMove>::type());
1377 /// Waits until either:
1378 /// 1: the enqueue turn preceding the given dequeue turn has arrived
1379 /// 2: the given deadline has arrived
1380 /// Case 1 returns true, case 2 returns false.
1381 template <class Clock>
1382 bool tryWaitForDequeueTurnUntil(
1383 const uint32_t turn,
1384 Atom<uint32_t>& spinCutoff,
1385 const bool updateSpinCutoff,
1386 const std::chrono::time_point<Clock>& when) noexcept {
1387 return sequencer_.tryWaitForTurn(
1388 turn * 2 + 1, spinCutoff, updateSpinCutoff, &when) !=
1389 TurnSequencer<Atom>::TryWaitResult::TIMEDOUT;
1392 bool mayDequeue(const uint32_t turn) const noexcept {
1393 return sequencer_.isTurn(turn * 2 + 1);
1397 /// Storage for a T constructed with placement new
1398 typename std::aligned_storage<sizeof(T),alignof(T)>::type contents_;
1400 /// Even turns are pushes, odd turns are pops
1401 TurnSequencer<Atom> sequencer_;
1404 return static_cast<T*>(static_cast<void*>(&contents_));
1407 void destroyContents() noexcept {
1411 // g++ doesn't seem to have std::is_nothrow_destructible yet
1414 memset(&contents_, 'Q', sizeof(T));
1418 /// Tag classes for dispatching to enqueue/dequeue implementation.
1419 struct ImplByRelocation {};
1420 struct ImplByMove {};
1422 /// enqueue using nothrow move construction.
1423 void enqueueImpl(const uint32_t turn,
1424 Atom<uint32_t>& spinCutoff,
1425 const bool updateSpinCutoff,
1427 ImplByMove) noexcept {
1428 sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
1429 new (&contents_) T(std::move(goner));
1430 sequencer_.completeTurn(turn * 2);
1433 /// enqueue by simulating nothrow move with relocation, followed by
1434 /// default construction to a noexcept relocation.
1435 void enqueueImpl(const uint32_t turn,
1436 Atom<uint32_t>& spinCutoff,
1437 const bool updateSpinCutoff,
1439 ImplByRelocation) noexcept {
1440 sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
1441 memcpy(&contents_, &goner, sizeof(T));
1442 sequencer_.completeTurn(turn * 2);
1446 /// dequeue by destructing followed by relocation. This version is preferred,
1447 /// because as much work as possible can be done before waiting.
1448 void dequeueImpl(uint32_t turn,
1449 Atom<uint32_t>& spinCutoff,
1450 const bool updateSpinCutoff,
1452 ImplByRelocation) noexcept {
1456 // unlikely, but if we don't complete our turn the queue will die
1458 sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
1459 memcpy(&elem, &contents_, sizeof(T));
1460 sequencer_.completeTurn(turn * 2 + 1);
1463 /// dequeue by nothrow move assignment.
1464 void dequeueImpl(uint32_t turn,
1465 Atom<uint32_t>& spinCutoff,
1466 const bool updateSpinCutoff,
1468 ImplByMove) noexcept {
1469 sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
1470 elem = std::move(*ptr());
1472 sequencer_.completeTurn(turn * 2 + 1);
1476 } // namespace detail
1478 } // namespace folly