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 needs 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)].mayEnqueue(
285 this->turn(ticket - offset, cap))) {
286 // A slot is ready. No need to expand.
289 this->popTicket_.load(std::memory_order_relaxed) + cap > ticket) {
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);
328 kDefaultMinDynamicCapacity = 10,
329 kDefaultExpansionMultiplier = 10,
334 // Info about closed slots arrays for use by lagging operations
335 ClosedArray* closed_;
337 void initQueue(const size_t cap, const size_t mult) {
338 this->stride_ = this->computeStride(cap);
339 this->slots_ = new Slot[cap + 2 * this->kSlotPadding];
340 this->dstate_.store(0);
341 this->dcapacity_.store(cap);
343 size_t maxClosed = 0;
344 for (size_t expanded = cap;
345 expanded < this->capacity_;
349 closed_ = (maxClosed > 0) ? new ClosedArray[maxClosed] : nullptr;
352 bool tryObtainReadyPushTicket(
353 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
357 ticket = this->pushTicket_.load(std::memory_order_acquire); // A
358 if (!trySeqlockReadSection(state, slots, cap, stride)) {
359 asm_volatile_pause();
363 // If there was an expansion with offset greater than this ticket,
364 // adjust accordingly
366 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
368 if (slots[this->idx((ticket - offset), cap, stride)].mayEnqueue(
369 this->turn(ticket - offset, cap))) {
371 if (this->pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
379 if (ticket != this->pushTicket_.load(std::memory_order_relaxed)) { // B
380 // Try again. Ticket changed.
384 // Try to expand unless the ticket is for a closed array
385 if (offset == getOffset(state)) {
386 if (tryExpand(state, cap)) {
387 // This or another thread started an expansion. Get up-to-date info.
396 bool tryObtainPromisedPushTicket(
397 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
401 ticket = this->pushTicket_.load(std::memory_order_acquire);
402 auto numPops = this->popTicket_.load(std::memory_order_acquire);
403 if (!trySeqlockReadSection(state, slots, cap, stride)) {
404 asm_volatile_pause();
408 const auto curCap = cap;
409 // If there was an expansion with offset greater than this ticket,
410 // adjust accordingly
412 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
414 int64_t n = ticket - numPops;
416 if (n >= static_cast<ssize_t>(cap)) {
417 if ((cap == curCap) && tryExpand(state, cap)) {
418 // This or another thread started an expansion. Start over.
426 if (this->pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
434 bool tryObtainReadyPopTicket(
435 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
439 ticket = this->popTicket_.load(std::memory_order_relaxed);
440 if (!trySeqlockReadSection(state, slots, cap, stride)) {
441 asm_volatile_pause();
445 // If there was an expansion after the corresponding push ticket
446 // was issued, adjust accordingly
448 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
450 if (slots[this->idx((ticket - offset), cap, stride)].mayDequeue(
451 this->turn(ticket - offset, cap))) {
452 if (this->popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
463 bool tryObtainPromisedPopTicket(
464 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
468 ticket = this->popTicket_.load(std::memory_order_acquire);
469 auto numPushes = this->pushTicket_.load(std::memory_order_acquire);
470 if (!trySeqlockReadSection(state, slots, cap, stride)) {
471 asm_volatile_pause();
476 // If there was an expansion after the corresponding push
477 // ticket was issued, adjust accordingly
478 maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
480 if (ticket >= numPushes) {
484 if (this->popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
491 /// Enqueues an element with a specific ticket number
492 template <typename ...Args>
493 void enqueueWithTicket(const uint64_t ticket, Args&&... args) noexcept {
500 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());
533 1 + std::max(this->pushTicket_.load(), this->popTicket_.load());
534 size_t newCapacity = std::min(dmult_ * cap, this->capacity_);
536 new (std::nothrow) Slot[newCapacity + 2 * this->kSlotPadding];
537 if (newSlots == nullptr) {
538 // Expansion failed. Restore the seqlock
539 this->dstate_.store(state);
542 // Successful expansion
543 // calculate the current ticket offset
544 uint64_t offset = getOffset(state);
545 // calculate index in closed array
546 int index = getNumClosed(state);
547 assert((index << 1) < (1 << kSeqlockBits));
548 // fill the info for the closed slots array
549 closed_[index].offset_ = offset;
550 closed_[index].slots_ = this->dslots_.load();
551 closed_[index].capacity_ = cap;
552 closed_[index].stride_ = this->dstride_.load();
553 // update the new slots array info
554 this->dslots_.store(newSlots);
555 this->dcapacity_.store(newCapacity);
556 this->dstride_.store(this->computeStride(newCapacity));
557 // Release the seqlock and record the new ticket offset
558 this->dstate_.store((ticket << kSeqlockBits) + (2 * (index + 1)));
560 } else { // failed to acquire seqlock
561 // Someone acaquired the seqlock. Go back to the caller and get
567 /// Seqlock read-only section
568 bool trySeqlockReadSection(
569 uint64_t& state, Slot*& slots, size_t& cap, int& stride
571 state = this->dstate_.load(std::memory_order_acquire);
576 // Start read-only section.
577 slots = this->dslots_.load(std::memory_order_relaxed);
578 cap = this->dcapacity_.load(std::memory_order_relaxed);
579 stride = this->dstride_.load(std::memory_order_relaxed);
580 // End of read-only section. Validate seqlock.
581 std::atomic_thread_fence(std::memory_order_acquire);
582 return (state == this->dstate_.load(std::memory_order_relaxed));
585 /// If there was an expansion after ticket was issued, update local variables
586 /// of the lagging operation using the most recent closed array with
587 /// offset <= ticket and return true. Otherwise, return false;
588 bool maybeUpdateFromClosed(
589 const uint64_t state,
590 const uint64_t ticket,
594 int& stride) noexcept {
595 offset = getOffset(state);
596 if (ticket >= offset) {
599 for (int i = getNumClosed(state) - 1; i >= 0; --i) {
600 offset = closed_[i].offset_;
601 if (offset <= ticket) {
602 slots = closed_[i].slots_;
603 cap = closed_[i].capacity_;
604 stride = closed_[i].stride_;
608 // A closed array with offset <= ticket should have been found
616 /// CRTP specialization of MPMCQueueBase
618 template <typename T, template <typename> class Atom, bool Dynamic>
621 template <typename> class Atom,
623 class MPMCQueueBase<Derived<T, Atom, Dynamic>> : boost::noncopyable {
625 // Note: Using CRTP static casts in several functions of this base
626 // template instead of making called functions virtual or duplicating
627 // the code of calling functions in the derived partially specialized
630 static_assert(std::is_nothrow_constructible<T,T&&>::value ||
631 folly::IsRelocatable<T>::value,
632 "T must be relocatable or have a noexcept move constructor");
635 typedef T value_type;
637 using Slot = detail::SingleElementQueue<T,Atom>;
639 explicit MPMCQueueBase(size_t queueCapacity)
640 : capacity_(queueCapacity)
646 if (queueCapacity == 0) {
647 throw std::invalid_argument(
648 "MPMCQueue with explicit capacity 0 is impossible"
649 // Stride computation in derived classes would sigfpe if capacity is 0
653 // ideally this would be a static assert, but g++ doesn't allow it
654 assert(alignof(MPMCQueue<T, Atom>) >= CacheLocality::kFalseSharingRange);
656 static_cast<uint8_t*>(static_cast<void*>(&popTicket_)) -
657 static_cast<uint8_t*>(static_cast<void*>(&pushTicket_)) >=
658 CacheLocality::kFalseSharingRange);
661 /// A default-constructed queue is useful because a usable (non-zero
662 /// capacity) queue can be moved onto it or swapped with it
663 MPMCQueueBase() noexcept
675 /// IMPORTANT: The move constructor is here to make it easier to perform
676 /// the initialization phase, it is not safe to use when there are any
677 /// concurrent accesses (this is not checked).
678 MPMCQueueBase(MPMCQueueBase<Derived<T,Atom,Dynamic>>&& rhs) noexcept
679 : capacity_(rhs.capacity_)
681 , stride_(rhs.stride_)
682 , dstate_(rhs.dstate_.load(std::memory_order_relaxed))
683 , dcapacity_(rhs.dcapacity_.load(std::memory_order_relaxed))
684 , pushTicket_(rhs.pushTicket_.load(std::memory_order_relaxed))
685 , popTicket_(rhs.popTicket_.load(std::memory_order_relaxed))
686 , pushSpinCutoff_(rhs.pushSpinCutoff_.load(std::memory_order_relaxed))
687 , popSpinCutoff_(rhs.popSpinCutoff_.load(std::memory_order_relaxed))
689 // relaxed ops are okay for the previous reads, since rhs queue can't
690 // be in concurrent use
694 rhs.slots_ = nullptr;
696 rhs.dstate_.store(0, std::memory_order_relaxed);
697 rhs.dcapacity_.store(0, std::memory_order_relaxed);
698 rhs.pushTicket_.store(0, std::memory_order_relaxed);
699 rhs.popTicket_.store(0, std::memory_order_relaxed);
700 rhs.pushSpinCutoff_.store(0, std::memory_order_relaxed);
701 rhs.popSpinCutoff_.store(0, std::memory_order_relaxed);
704 /// IMPORTANT: The move operator is here to make it easier to perform
705 /// the initialization phase, it is not safe to use when there are any
706 /// concurrent accesses (this is not checked).
707 MPMCQueueBase<Derived<T,Atom,Dynamic>> const& operator=
708 (MPMCQueueBase<Derived<T,Atom,Dynamic>>&& rhs) {
710 this->~MPMCQueueBase();
711 new (this) MPMCQueueBase(std::move(rhs));
716 /// MPMCQueue can only be safely destroyed when there are no
717 /// pending enqueuers or dequeuers (this is not checked).
722 /// Returns the number of writes (including threads that are blocked waiting
723 /// to write) minus the number of reads (including threads that are blocked
724 /// waiting to read). So effectively, it becomes:
725 /// elements in queue + pending(calls to write) - pending(calls to read).
726 /// If nothing is pending, then the method returns the actual number of
727 /// elements in the queue.
728 /// The returned value can be negative if there are no writers and the queue
729 /// is empty, but there is one reader that is blocked waiting to read (in
730 /// which case, the returned size will be -1).
731 ssize_t size() const noexcept {
732 // since both pushes and pops increase monotonically, we can get a
733 // consistent snapshot either by bracketing a read of popTicket_ with
734 // two reads of pushTicket_ that return the same value, or the other
735 // way around. We maximize our chances by alternately attempting
737 uint64_t pushes = pushTicket_.load(std::memory_order_acquire); // A
738 uint64_t pops = popTicket_.load(std::memory_order_acquire); // B
740 uint64_t nextPushes = pushTicket_.load(std::memory_order_acquire); // C
741 if (pushes == nextPushes) {
742 // pushTicket_ didn't change from A (or the previous C) to C,
743 // so we can linearize at B (or D)
744 return ssize_t(pushes - pops);
747 uint64_t nextPops = popTicket_.load(std::memory_order_acquire); // D
748 if (pops == nextPops) {
749 // popTicket_ didn't chance from B (or the previous D), so we
750 // can linearize at C
751 return ssize_t(pushes - pops);
757 /// Returns true if there are no items available for dequeue
758 bool isEmpty() const noexcept {
762 /// Returns true if there is currently no empty space to enqueue
763 bool isFull() const noexcept {
764 // careful with signed -> unsigned promotion, since size can be negative
765 return size() >= static_cast<ssize_t>(capacity_);
768 /// Returns is a guess at size() for contexts that don't need a precise
769 /// value, such as stats. More specifically, it returns the number of writes
770 /// minus the number of reads, but after reading the number of writes, more
771 /// writers could have came before the number of reads was sampled,
772 /// and this method doesn't protect against such case.
773 /// The returned value can be negative.
774 ssize_t sizeGuess() const noexcept {
775 return writeCount() - readCount();
779 size_t capacity() const noexcept {
783 /// Doesn't change for non-dynamic
784 size_t allocatedCapacity() const noexcept {
788 /// Returns the total number of calls to blockingWrite or successful
789 /// calls to write, including those blockingWrite calls that are
790 /// currently blocking
791 uint64_t writeCount() const noexcept {
792 return pushTicket_.load(std::memory_order_acquire);
795 /// Returns the total number of calls to blockingRead or successful
796 /// calls to read, including those blockingRead calls that are currently
798 uint64_t readCount() const noexcept {
799 return popTicket_.load(std::memory_order_acquire);
802 /// Enqueues a T constructed from args, blocking until space is
803 /// available. Note that this method signature allows enqueue via
804 /// move, if args is a T rvalue, via copy, if args is a T lvalue, or
805 /// via emplacement if args is an initializer list that can be passed
806 /// to a T constructor.
807 template <typename ...Args>
808 void blockingWrite(Args&&... args) noexcept {
809 enqueueWithTicketBase(pushTicket_++, slots_, capacity_, stride_,
810 std::forward<Args>(args)...);
813 /// If an item can be enqueued with no blocking, does so and returns
814 /// true, otherwise returns false. This method is similar to
815 /// writeIfNotFull, but if you don't have a specific need for that
816 /// method you should use this one.
818 /// One of the common usages of this method is to enqueue via the
819 /// move constructor, something like q.write(std::move(x)). If write
820 /// returns false because the queue is full then x has not actually been
821 /// consumed, which looks strange. To understand why it is actually okay
822 /// to use x afterward, remember that std::move is just a typecast that
823 /// provides an rvalue reference that enables use of a move constructor
824 /// or operator. std::move doesn't actually move anything. It could
825 /// more accurately be called std::rvalue_cast or std::move_permission.
826 template <typename ...Args>
827 bool write(Args&&... args) noexcept {
832 if (static_cast<Derived<T,Atom,Dynamic>*>(this)->
833 tryObtainReadyPushTicket(ticket, slots, cap, stride)) {
834 // we have pre-validated that the ticket won't block
835 enqueueWithTicketBase(ticket, slots, cap, stride,
836 std::forward<Args>(args)...);
843 template <class Clock, typename... Args>
844 bool tryWriteUntil(const std::chrono::time_point<Clock>& when,
845 Args&&... args) noexcept {
850 if (tryObtainPromisedPushTicketUntil(ticket, slots, cap, stride, when)) {
851 // we have pre-validated that the ticket won't block, or rather that
852 // it won't block longer than it takes another thread to dequeue an
853 // element from the slot it identifies.
854 enqueueWithTicketBase(ticket, slots, cap, stride,
855 std::forward<Args>(args)...);
862 /// If the queue is not full, enqueues and returns true, otherwise
863 /// returns false. Unlike write this method can be blocked by another
864 /// thread, specifically a read that has linearized (been assigned
865 /// a ticket) but not yet completed. If you don't really need this
866 /// function you should probably use write.
868 /// MPMCQueue isn't lock-free, so just because a read operation has
869 /// linearized (and isFull is false) doesn't mean that space has been
870 /// made available for another write. In this situation write will
871 /// return false, but writeIfNotFull will wait for the dequeue to finish.
872 /// This method is required if you are composing queues and managing
873 /// your own wakeup, because it guarantees that after every successful
874 /// write a readIfNotEmpty will succeed.
875 template <typename ...Args>
876 bool writeIfNotFull(Args&&... args) noexcept {
881 if (static_cast<Derived<T,Atom,Dynamic>*>(this)->
882 tryObtainPromisedPushTicket(ticket, slots, cap, stride)) {
883 // some other thread is already dequeuing the slot into which we
884 // are going to enqueue, but we might have to wait for them to finish
885 enqueueWithTicketBase(ticket, slots, cap, stride,
886 std::forward<Args>(args)...);
893 /// Moves a dequeued element onto elem, blocking until an element
895 void blockingRead(T& elem) noexcept {
897 static_cast<Derived<T,Atom,Dynamic>*>(this)->
898 blockingReadWithTicket(ticket, elem);
901 /// Same as blockingRead() but also records the ticket nunmer
902 void blockingReadWithTicket(uint64_t& ticket, T& elem) noexcept {
903 assert(capacity_ != 0);
904 ticket = popTicket_++;
905 dequeueWithTicketBase(ticket, slots_, capacity_, stride_, elem);
908 /// If an item can be dequeued with no blocking, does so and returns
909 /// true, otherwise returns false.
910 bool read(T& elem) noexcept {
912 return readAndGetTicket(ticket, elem);
915 /// Same as read() but also records the ticket nunmer
916 bool readAndGetTicket(uint64_t& ticket, T& elem) noexcept {
920 if (static_cast<Derived<T,Atom,Dynamic>*>(this)->
921 tryObtainReadyPopTicket(ticket, slots, cap, stride)) {
922 // the ticket has been pre-validated to not block
923 dequeueWithTicketBase(ticket, slots, cap, stride, elem);
930 template <class Clock, typename... Args>
932 const std::chrono::time_point<Clock>& when,
938 if (tryObtainPromisedPopTicketUntil(ticket, slots, cap, stride, when)) {
939 // we have pre-validated that the ticket won't block, or rather that
940 // it won't block longer than it takes another thread to enqueue an
941 // element on the slot it identifies.
942 dequeueWithTicketBase(ticket, slots, cap, stride, elem);
949 /// If the queue is not empty, dequeues and returns true, otherwise
950 /// returns false. If the matching write is still in progress then this
951 /// method may block waiting for it. If you don't rely on being able
952 /// to dequeue (such as by counting completed write) then you should
954 bool readIfNotEmpty(T& elem) noexcept {
959 if (static_cast<Derived<T,Atom,Dynamic>*>(this)->
960 tryObtainPromisedPopTicket(ticket, slots, cap, stride)) {
961 // the matching enqueue already has a ticket, but might not be done
962 dequeueWithTicketBase(ticket, slots, cap, stride, elem);
971 /// Once every kAdaptationFreq we will spin longer, to try to estimate
972 /// the proper spin backoff
973 kAdaptationFreq = 128,
975 /// To avoid false sharing in slots_ with neighboring memory
976 /// allocations, we pad it with this many SingleElementQueue-s at
978 kSlotPadding = (CacheLocality::kFalseSharingRange - 1) / sizeof(Slot) + 1
981 /// The maximum number of items in the queue at once
982 size_t FOLLY_ALIGN_TO_AVOID_FALSE_SHARING capacity_;
984 /// Anonymous union for use when Dynamic = false and true, respectively
986 /// An array of capacity_ SingleElementQueue-s, each of which holds
987 /// either 0 or 1 item. We over-allocate by 2 * kSlotPadding and don't
988 /// touch the slots at either end, to avoid false sharing
990 /// Current dynamic slots array of dcapacity_ SingleElementQueue-s
994 /// Anonymous union for use when Dynamic = false and true, respectively
996 /// The number of slots_ indices that we advance for each ticket, to
997 /// avoid false sharing. Ideally slots_[i] and slots_[i + stride_]
998 /// aren't on the same cache line
1004 /// The following two memebers are used by dynamic MPMCQueue.
1005 /// Ideally they should be in MPMCQueue<T,Atom,true>, but we get
1006 /// better cache locality if they are in the same cache line as
1007 /// dslots_ and dstride_.
1009 /// Dynamic state. A packed seqlock and ticket offset
1010 Atom<uint64_t> dstate_;
1011 /// Dynamic capacity
1012 Atom<size_t> dcapacity_;
1014 /// Enqueuers get tickets from here
1015 Atom<uint64_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING pushTicket_;
1017 /// Dequeuers get tickets from here
1018 Atom<uint64_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING popTicket_;
1020 /// This is how many times we will spin before using FUTEX_WAIT when
1021 /// the queue is full on enqueue, adaptively computed by occasionally
1022 /// spinning for longer and smoothing with an exponential moving average
1023 Atom<uint32_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING pushSpinCutoff_;
1025 /// The adaptive spin cutoff when the queue is empty on dequeue
1026 Atom<uint32_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING popSpinCutoff_;
1028 /// Alignment doesn't prevent false sharing at the end of the struct,
1029 /// so fill out the last cache line
1030 char padding_[CacheLocality::kFalseSharingRange - sizeof(Atom<uint32_t>)];
1032 /// We assign tickets in increasing order, but we don't want to
1033 /// access neighboring elements of slots_ because that will lead to
1034 /// false sharing (multiple cores accessing the same cache line even
1035 /// though they aren't accessing the same bytes in that cache line).
1036 /// To avoid this we advance by stride slots per ticket.
1038 /// We need gcd(capacity, stride) to be 1 so that we will use all
1039 /// of the slots. We ensure this by only considering prime strides,
1040 /// which either have no common divisors with capacity or else have
1041 /// a zero remainder after dividing by capacity. That is sufficient
1042 /// to guarantee correctness, but we also want to actually spread the
1043 /// accesses away from each other to avoid false sharing (consider a
1044 /// stride of 7 with a capacity of 8). To that end we try a few taking
1045 /// care to observe that advancing by -1 is as bad as advancing by 1
1046 /// when in comes to false sharing.
1048 /// The simple way to avoid false sharing would be to pad each
1049 /// SingleElementQueue, but since we have capacity_ of them that could
1050 /// waste a lot of space.
1051 static int computeStride(size_t capacity) noexcept {
1052 static const int smallPrimes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };
1056 for (int stride : smallPrimes) {
1057 if ((stride % capacity) == 0 || (capacity % stride) == 0) {
1060 size_t sep = stride % capacity;
1061 sep = std::min(sep, capacity - sep);
1062 if (sep > bestSep) {
1063 bestStride = stride;
1070 /// Returns the index into slots_ that should be used when enqueuing or
1071 /// dequeuing with the specified ticket
1072 size_t idx(uint64_t ticket, size_t cap, int stride) noexcept {
1073 return ((ticket * stride) % cap) + kSlotPadding;
1076 /// Maps an enqueue or dequeue ticket to the turn should be used at the
1077 /// corresponding SingleElementQueue
1078 uint32_t turn(uint64_t ticket, size_t cap) noexcept {
1080 return uint32_t(ticket / cap);
1083 /// Tries to obtain a push ticket for which SingleElementQueue::enqueue
1084 /// won't block. Returns true on immediate success, false on immediate
1086 bool tryObtainReadyPushTicket(
1087 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
1089 ticket = pushTicket_.load(std::memory_order_acquire); // A
1094 if (!slots[idx(ticket, cap, stride)]
1095 .mayEnqueue(turn(ticket, cap))) {
1096 // if we call enqueue(ticket, ...) on the SingleElementQueue
1097 // right now it would block, but this might no longer be the next
1098 // ticket. We can increase the chance of tryEnqueue success under
1099 // contention (without blocking) by rechecking the ticket dispenser
1101 ticket = pushTicket_.load(std::memory_order_acquire); // B
1102 if (prev == ticket) {
1103 // mayEnqueue was bracketed by two reads (A or prev B or prev
1104 // failing CAS to B), so we are definitely unable to enqueue
1108 // we will bracket the mayEnqueue check with a read (A or prev B
1109 // or prev failing CAS) and the following CAS. If the CAS fails
1110 // it will effect a load of pushTicket_
1111 if (pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
1118 /// Tries until when to obtain a push ticket for which
1119 /// SingleElementQueue::enqueue won't block. Returns true on success, false
1121 /// ticket is filled on success AND failure.
1122 template <class Clock>
1123 bool tryObtainPromisedPushTicketUntil(
1124 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride,
1125 const std::chrono::time_point<Clock>& when
1127 bool deadlineReached = false;
1128 while (!deadlineReached) {
1129 if (static_cast<Derived<T,Atom,Dynamic>*>(this)->
1130 tryObtainPromisedPushTicket(ticket, slots, cap, stride)) {
1133 // ticket is a blocking ticket until the preceding ticket has been
1134 // processed: wait until this ticket's turn arrives. We have not reserved
1135 // this ticket so we will have to re-attempt to get a non-blocking ticket
1136 // if we wake up before we time-out.
1137 deadlineReached = !slots[idx(ticket, cap, stride)]
1138 .tryWaitForEnqueueTurnUntil(turn(ticket, cap), pushSpinCutoff_,
1139 (ticket % kAdaptationFreq) == 0, when);
1144 /// Tries to obtain a push ticket which can be satisfied if all
1145 /// in-progress pops complete. This function does not block, but
1146 /// blocking may be required when using the returned ticket if some
1147 /// other thread's pop is still in progress (ticket has been granted but
1148 /// pop has not yet completed).
1149 bool tryObtainPromisedPushTicket(
1150 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
1152 auto numPushes = pushTicket_.load(std::memory_order_acquire); // A
1158 const auto numPops = popTicket_.load(std::memory_order_acquire); // B
1159 // n will be negative if pops are pending
1160 const int64_t n = int64_t(numPushes - numPops);
1161 if (n >= static_cast<ssize_t>(capacity_)) {
1162 // Full, linearize at B. We don't need to recheck the read we
1163 // performed at A, because if numPushes was stale at B then the
1164 // real numPushes value is even worse
1167 if (pushTicket_.compare_exchange_strong(numPushes, numPushes + 1)) {
1173 /// Tries to obtain a pop ticket for which SingleElementQueue::dequeue
1174 /// won't block. Returns true on immediate success, false on immediate
1176 bool tryObtainReadyPopTicket(
1177 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
1179 ticket = popTicket_.load(std::memory_order_acquire);
1184 if (!slots[idx(ticket, cap, stride)]
1185 .mayDequeue(turn(ticket, cap))) {
1187 ticket = popTicket_.load(std::memory_order_acquire);
1188 if (prev == ticket) {
1192 if (popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
1199 /// Tries until when to obtain a pop ticket for which
1200 /// SingleElementQueue::dequeue won't block. Returns true on success, false
1202 /// ticket is filled on success AND failure.
1203 template <class Clock>
1204 bool tryObtainPromisedPopTicketUntil(
1209 const std::chrono::time_point<Clock>& when) noexcept {
1210 bool deadlineReached = false;
1211 while (!deadlineReached) {
1212 if (static_cast<Derived<T, Atom, Dynamic>*>(this)
1213 ->tryObtainPromisedPopTicket(ticket, slots, cap, stride)) {
1216 // ticket is a blocking ticket until the preceding ticket has been
1217 // processed: wait until this ticket's turn arrives. We have not reserved
1218 // this ticket so we will have to re-attempt to get a non-blocking ticket
1219 // if we wake up before we time-out.
1221 !slots[idx(ticket, cap, stride)].tryWaitForDequeueTurnUntil(
1224 (ticket % kAdaptationFreq) == 0,
1230 /// Similar to tryObtainReadyPopTicket, but returns a pop ticket whose
1231 /// corresponding push ticket has already been handed out, rather than
1232 /// returning one whose corresponding push ticket has already been
1233 /// completed. This means that there is a possibility that the caller
1234 /// will block when using the ticket, but it allows the user to rely on
1235 /// the fact that if enqueue has succeeded, tryObtainPromisedPopTicket
1236 /// will return true. The "try" part of this is that we won't have
1237 /// to block waiting for someone to call enqueue, although we might
1238 /// have to block waiting for them to finish executing code inside the
1239 /// MPMCQueue itself.
1240 bool tryObtainPromisedPopTicket(
1241 uint64_t& ticket, Slot*& slots, size_t& cap, int& stride
1243 auto numPops = popTicket_.load(std::memory_order_acquire); // A
1249 const auto numPushes = pushTicket_.load(std::memory_order_acquire); // B
1250 if (numPops >= numPushes) {
1251 // Empty, or empty with pending pops. Linearize at B. We don't
1252 // need to recheck the read we performed at A, because if numPops
1253 // is stale then the fresh value is larger and the >= is still true
1256 if (popTicket_.compare_exchange_strong(numPops, numPops + 1)) {
1262 // Given a ticket, constructs an enqueued item using args
1263 template <typename ...Args>
1264 void enqueueWithTicketBase(
1265 uint64_t ticket, Slot* slots, size_t cap, int stride, Args&&... args
1267 slots[idx(ticket, cap, stride)]
1268 .enqueue(turn(ticket, cap),
1270 (ticket % kAdaptationFreq) == 0,
1271 std::forward<Args>(args)...);
1274 // To support tracking ticket numbers in MPMCPipelineStageImpl
1275 template <typename ...Args>
1276 void enqueueWithTicket(uint64_t ticket, Args&&... args) noexcept {
1277 enqueueWithTicketBase(ticket, slots_, capacity_, stride_,
1278 std::forward<Args>(args)...);
1281 // Given a ticket, dequeues the corresponding element
1282 void dequeueWithTicketBase(
1283 uint64_t ticket, Slot* slots, size_t cap, int stride, T& elem
1286 slots[idx(ticket, cap, stride)]
1287 .dequeue(turn(ticket, cap),
1289 (ticket % kAdaptationFreq) == 0,
1294 /// SingleElementQueue implements a blocking queue that holds at most one
1295 /// item, and that requires its users to assign incrementing identifiers
1296 /// (turns) to each enqueue and dequeue operation. Note that the turns
1297 /// used by SingleElementQueue are doubled inside the TurnSequencer
1298 template <typename T, template <typename> class Atom>
1299 struct SingleElementQueue {
1301 ~SingleElementQueue() noexcept {
1302 if ((sequencer_.uncompletedTurnLSB() & 1) == 1) {
1303 // we are pending a dequeue, so we have a constructed item
1308 /// enqueue using in-place noexcept construction
1311 typename = typename std::enable_if<
1312 std::is_nothrow_constructible<T, Args...>::value>::type>
1313 void enqueue(const uint32_t turn,
1314 Atom<uint32_t>& spinCutoff,
1315 const bool updateSpinCutoff,
1316 Args&&... args) noexcept {
1317 sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
1318 new (&contents_) T(std::forward<Args>(args)...);
1319 sequencer_.completeTurn(turn * 2);
1322 /// enqueue using move construction, either real (if
1323 /// is_nothrow_move_constructible) or simulated using relocation and
1324 /// default construction (if IsRelocatable and is_nothrow_constructible)
1326 typename = typename std::enable_if<
1327 (folly::IsRelocatable<T>::value &&
1328 std::is_nothrow_constructible<T>::value) ||
1329 std::is_nothrow_constructible<T, T&&>::value>::type>
1331 const uint32_t turn,
1332 Atom<uint32_t>& spinCutoff,
1333 const bool updateSpinCutoff,
1334 T&& goner) noexcept {
1340 typename std::conditional<std::is_nothrow_constructible<T,T&&>::value,
1341 ImplByMove, ImplByRelocation>::type());
1344 /// Waits until either:
1345 /// 1: the dequeue turn preceding the given enqueue turn has arrived
1346 /// 2: the given deadline has arrived
1347 /// Case 1 returns true, case 2 returns false.
1348 template <class Clock>
1349 bool tryWaitForEnqueueTurnUntil(
1350 const uint32_t turn,
1351 Atom<uint32_t>& spinCutoff,
1352 const bool updateSpinCutoff,
1353 const std::chrono::time_point<Clock>& when) noexcept {
1354 return sequencer_.tryWaitForTurn(
1355 turn * 2, spinCutoff, updateSpinCutoff, &when) !=
1356 TurnSequencer<Atom>::TryWaitResult::TIMEDOUT;
1359 bool mayEnqueue(const uint32_t turn) const noexcept {
1360 return sequencer_.isTurn(turn * 2);
1363 void dequeue(uint32_t turn,
1364 Atom<uint32_t>& spinCutoff,
1365 const bool updateSpinCutoff,
1371 typename std::conditional<folly::IsRelocatable<T>::value,
1373 ImplByMove>::type());
1376 /// Waits until either:
1377 /// 1: the enqueue turn preceding the given dequeue turn has arrived
1378 /// 2: the given deadline has arrived
1379 /// Case 1 returns true, case 2 returns false.
1380 template <class Clock>
1381 bool tryWaitForDequeueTurnUntil(
1382 const uint32_t turn,
1383 Atom<uint32_t>& spinCutoff,
1384 const bool updateSpinCutoff,
1385 const std::chrono::time_point<Clock>& when) noexcept {
1386 return sequencer_.tryWaitForTurn(
1387 turn * 2 + 1, spinCutoff, updateSpinCutoff, &when) !=
1388 TurnSequencer<Atom>::TryWaitResult::TIMEDOUT;
1391 bool mayDequeue(const uint32_t turn) const noexcept {
1392 return sequencer_.isTurn(turn * 2 + 1);
1396 /// Storage for a T constructed with placement new
1397 typename std::aligned_storage<sizeof(T),alignof(T)>::type contents_;
1399 /// Even turns are pushes, odd turns are pops
1400 TurnSequencer<Atom> sequencer_;
1403 return static_cast<T*>(static_cast<void*>(&contents_));
1406 void destroyContents() noexcept {
1410 // g++ doesn't seem to have std::is_nothrow_destructible yet
1413 memset(&contents_, 'Q', sizeof(T));
1417 /// Tag classes for dispatching to enqueue/dequeue implementation.
1418 struct ImplByRelocation {};
1419 struct ImplByMove {};
1421 /// enqueue using nothrow move construction.
1422 void enqueueImpl(const uint32_t turn,
1423 Atom<uint32_t>& spinCutoff,
1424 const bool updateSpinCutoff,
1426 ImplByMove) noexcept {
1427 sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
1428 new (&contents_) T(std::move(goner));
1429 sequencer_.completeTurn(turn * 2);
1432 /// enqueue by simulating nothrow move with relocation, followed by
1433 /// default construction to a noexcept relocation.
1434 void enqueueImpl(const uint32_t turn,
1435 Atom<uint32_t>& spinCutoff,
1436 const bool updateSpinCutoff,
1438 ImplByRelocation) noexcept {
1439 sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
1440 memcpy(&contents_, &goner, sizeof(T));
1441 sequencer_.completeTurn(turn * 2);
1445 /// dequeue by destructing followed by relocation. This version is preferred,
1446 /// because as much work as possible can be done before waiting.
1447 void dequeueImpl(uint32_t turn,
1448 Atom<uint32_t>& spinCutoff,
1449 const bool updateSpinCutoff,
1451 ImplByRelocation) noexcept {
1455 // unlikely, but if we don't complete our turn the queue will die
1457 sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
1458 memcpy(&elem, &contents_, sizeof(T));
1459 sequencer_.completeTurn(turn * 2 + 1);
1462 /// dequeue by nothrow move assignment.
1463 void dequeueImpl(uint32_t turn,
1464 Atom<uint32_t>& spinCutoff,
1465 const bool updateSpinCutoff,
1467 ImplByMove) noexcept {
1468 sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
1469 elem = std::move(*ptr());
1471 sequencer_.completeTurn(turn * 2 + 1);
1475 } // namespace detail
1477 } // namespace folly