2 * Copyright 2014 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
22 #include <boost/noncopyable.hpp>
25 #include <type_traits>
28 #include <folly/Traits.h>
29 #include <folly/detail/CacheLocality.h>
30 #include <folly/detail/Futex.h>
36 template<typename T, template<typename> class Atom>
37 class SingleElementQueue;
39 template <typename T> class MPMCPipelineStageImpl;
43 /// MPMCQueue<T> is a high-performance bounded concurrent queue that
44 /// supports multiple producers, multiple consumers, and optional blocking.
45 /// The queue has a fixed capacity, for which all memory will be allocated
46 /// up front. The bulk of the work of enqueuing and dequeuing can be
47 /// performed in parallel.
49 /// The underlying implementation uses a ticket dispenser for the head and
50 /// the tail, spreading accesses across N single-element queues to produce
51 /// a queue with capacity N. The ticket dispensers use atomic increment,
52 /// which is more robust to contention than a CAS loop. Each of the
53 /// single-element queues uses its own CAS to serialize access, with an
54 /// adaptive spin cutoff. When spinning fails on a single-element queue
55 /// it uses futex()'s _BITSET operations to reduce unnecessary wakeups
56 /// even if multiple waiters are present on an individual queue (such as
57 /// when the MPMCQueue's capacity is smaller than the number of enqueuers
60 /// NOEXCEPT INTERACTION: Ticket-based queues separate the assignment
61 /// of In benchmarks (contained in tao/queues/ConcurrentQueueTests)
62 /// it handles 1 to 1, 1 to N, N to 1, and N to M thread counts better
63 /// than any of the alternatives present in fbcode, for both small (~10)
64 /// and large capacities. In these benchmarks it is also faster than
65 /// tbb::concurrent_bounded_queue for all configurations. When there are
66 /// many more threads than cores, MPMCQueue is _much_ faster than the tbb
67 /// queue because it uses futex() to block and unblock waiting threads,
68 /// rather than spinning with sched_yield.
70 /// queue positions from the actual construction of the in-queue elements,
71 /// which means that the T constructor used during enqueue must not throw
72 /// an exception. This is enforced at compile time using type traits,
73 /// which requires that T be adorned with accurate noexcept information.
74 /// If your type does not use noexcept, you will have to wrap it in
75 /// something that provides the guarantee. We provide an alternate
76 /// safe implementation for types that don't use noexcept but that are
77 /// marked folly::IsRelocatable and boost::has_nothrow_constructor,
78 /// which is common for folly types. In particular, if you can declare
79 /// FOLLY_ASSUME_FBVECTOR_COMPATIBLE then your type can be put in
82 template<typename> class Atom = std::atomic>
83 class MPMCQueue : boost::noncopyable {
85 static_assert(std::is_nothrow_constructible<T,T&&>::value ||
86 folly::IsRelocatable<T>::value,
87 "T must be relocatable or have a noexcept move constructor");
89 friend class detail::MPMCPipelineStageImpl<T>;
93 explicit MPMCQueue(size_t queueCapacity)
94 : capacity_(queueCapacity)
95 , slots_(new detail::SingleElementQueue<T,Atom>[queueCapacity +
97 , stride_(computeStride(queueCapacity))
103 // ideally this would be a static assert, but g++ doesn't allow it
104 assert(alignof(MPMCQueue<T,Atom>)
105 >= detail::CacheLocality::kFalseSharingRange);
106 assert(static_cast<uint8_t*>(static_cast<void*>(&popTicket_))
107 - static_cast<uint8_t*>(static_cast<void*>(&pushTicket_))
108 >= detail::CacheLocality::kFalseSharingRange);
111 /// A default-constructed queue is useful because a usable (non-zero
112 /// capacity) queue can be moved onto it or swapped with it
123 /// IMPORTANT: The move constructor is here to make it easier to perform
124 /// the initialization phase, it is not safe to use when there are any
125 /// concurrent accesses (this is not checked).
126 MPMCQueue(MPMCQueue<T,Atom>&& rhs) noexcept
127 : capacity_(rhs.capacity_)
129 , stride_(rhs.stride_)
130 , pushTicket_(rhs.pushTicket_.load(std::memory_order_relaxed))
131 , popTicket_(rhs.popTicket_.load(std::memory_order_relaxed))
132 , pushSpinCutoff_(rhs.pushSpinCutoff_.load(std::memory_order_relaxed))
133 , popSpinCutoff_(rhs.popSpinCutoff_.load(std::memory_order_relaxed))
135 // relaxed ops are okay for the previous reads, since rhs queue can't
136 // be in concurrent use
140 rhs.slots_ = nullptr;
142 rhs.pushTicket_.store(0, std::memory_order_relaxed);
143 rhs.popTicket_.store(0, std::memory_order_relaxed);
144 rhs.pushSpinCutoff_.store(0, std::memory_order_relaxed);
145 rhs.popSpinCutoff_.store(0, std::memory_order_relaxed);
148 /// IMPORTANT: The move operator is here to make it easier to perform
149 /// the initialization phase, it is not safe to use when there are any
150 /// concurrent accesses (this is not checked).
151 MPMCQueue<T,Atom> const& operator= (MPMCQueue<T,Atom>&& rhs) {
154 new (this) MPMCQueue(std::move(rhs));
159 /// MPMCQueue can only be safely destroyed when there are no
160 /// pending enqueuers or dequeuers (this is not checked).
165 /// Returns the number of successful reads minus the number of successful
166 /// writes. Waiting blockingRead and blockingWrite calls are included,
167 /// so this value can be negative.
168 ssize_t size() const noexcept {
169 // since both pushes and pops increase monotonically, we can get a
170 // consistent snapshot either by bracketing a read of popTicket_ with
171 // two reads of pushTicket_ that return the same value, or the other
172 // way around. We maximize our chances by alternately attempting
174 uint64_t pushes = pushTicket_.load(std::memory_order_acquire); // A
175 uint64_t pops = popTicket_.load(std::memory_order_acquire); // B
177 uint64_t nextPushes = pushTicket_.load(std::memory_order_acquire); // C
178 if (pushes == nextPushes) {
179 // pushTicket_ didn't change from A (or the previous C) to C,
180 // so we can linearize at B (or D)
181 return pushes - pops;
184 uint64_t nextPops = popTicket_.load(std::memory_order_acquire); // D
185 if (pops == nextPops) {
186 // popTicket_ didn't chance from B (or the previous D), so we
187 // can linearize at C
188 return pushes - pops;
194 /// Returns true if there are no items available for dequeue
195 bool isEmpty() const noexcept {
199 /// Returns true if there is currently no empty space to enqueue
200 bool isFull() const noexcept {
201 // careful with signed -> unsigned promotion, since size can be negative
202 return size() >= static_cast<ssize_t>(capacity_);
205 /// Returns is a guess at size() for contexts that don't need a precise
206 /// value, such as stats.
207 ssize_t sizeGuess() const noexcept {
208 return writeCount() - readCount();
212 size_t capacity() const noexcept {
216 /// Returns the total number of calls to blockingWrite or successful
217 /// calls to write, including those blockingWrite calls that are
218 /// currently blocking
219 uint64_t writeCount() const noexcept {
220 return pushTicket_.load(std::memory_order_acquire);
223 /// Returns the total number of calls to blockingRead or successful
224 /// calls to read, including those blockingRead calls that are currently
226 uint64_t readCount() const noexcept {
227 return popTicket_.load(std::memory_order_acquire);
230 /// Enqueues a T constructed from args, blocking until space is
231 /// available. Note that this method signature allows enqueue via
232 /// move, if args is a T rvalue, via copy, if args is a T lvalue, or
233 /// via emplacement if args is an initializer list that can be passed
234 /// to a T constructor.
235 template <typename ...Args>
236 void blockingWrite(Args&&... args) noexcept {
237 enqueueWithTicket(pushTicket_++, std::forward<Args>(args)...);
240 /// If an item can be enqueued with no blocking, does so and returns
241 /// true, otherwise returns false. This method is similar to
242 /// writeIfNotFull, but if you don't have a specific need for that
243 /// method you should use this one.
245 /// One of the common usages of this method is to enqueue via the
246 /// move constructor, something like q.write(std::move(x)). If write
247 /// returns false because the queue is full then x has not actually been
248 /// consumed, which looks strange. To understand why it is actually okay
249 /// to use x afterward, remember that std::move is just a typecast that
250 /// provides an rvalue reference that enables use of a move constructor
251 /// or operator. std::move doesn't actually move anything. It could
252 /// more accurately be called std::rvalue_cast or std::move_permission.
253 template <typename ...Args>
254 bool write(Args&&... args) noexcept {
256 if (tryObtainReadyPushTicket(ticket)) {
257 // we have pre-validated that the ticket won't block
258 enqueueWithTicket(ticket, std::forward<Args>(args)...);
265 /// If the queue is not full, enqueues and returns true, otherwise
266 /// returns false. Unlike write this method can be blocked by another
267 /// thread, specifically a read that has linearized (been assigned
268 /// a ticket) but not yet completed. If you don't really need this
269 /// function you should probably use write.
271 /// MPMCQueue isn't lock-free, so just because a read operation has
272 /// linearized (and isFull is false) doesn't mean that space has been
273 /// made available for another write. In this situation write will
274 /// return false, but writeIfNotFull will wait for the dequeue to finish.
275 /// This method is required if you are composing queues and managing
276 /// your own wakeup, because it guarantees that after every successful
277 /// write a readIfNotFull will succeed.
278 template <typename ...Args>
279 bool writeIfNotFull(Args&&... args) noexcept {
281 if (tryObtainPromisedPushTicket(ticket)) {
282 // some other thread is already dequeuing the slot into which we
283 // are going to enqueue, but we might have to wait for them to finish
284 enqueueWithTicket(ticket, std::forward<Args>(args)...);
291 /// Moves a dequeued element onto elem, blocking until an element
293 void blockingRead(T& elem) noexcept {
294 dequeueWithTicket(popTicket_++, elem);
297 /// If an item can be dequeued with no blocking, does so and returns
298 /// true, otherwise returns false.
299 bool read(T& elem) noexcept {
301 if (tryObtainReadyPopTicket(ticket)) {
302 // the ticket has been pre-validated to not block
303 dequeueWithTicket(ticket, elem);
310 /// If the queue is not empty, dequeues and returns true, otherwise
311 /// returns false. If the matching write is still in progress then this
312 /// method may block waiting for it. If you don't rely on being able
313 /// to dequeue (such as by counting completed write) then you should
315 bool readIfNotEmpty(T& elem) noexcept {
317 if (tryObtainPromisedPopTicket(ticket)) {
318 // the matching enqueue already has a ticket, but might not be done
319 dequeueWithTicket(ticket, elem);
328 /// Once every kAdaptationFreq we will spin longer, to try to estimate
329 /// the proper spin backoff
330 kAdaptationFreq = 128,
332 /// To avoid false sharing in slots_ with neighboring memory
333 /// allocations, we pad it with this many SingleElementQueue-s at
335 kSlotPadding = (detail::CacheLocality::kFalseSharingRange - 1)
336 / sizeof(detail::SingleElementQueue<T,Atom>) + 1
339 /// The maximum number of items in the queue at once
340 size_t FOLLY_ALIGN_TO_AVOID_FALSE_SHARING capacity_;
342 /// An array of capacity_ SingleElementQueue-s, each of which holds
343 /// either 0 or 1 item. We over-allocate by 2 * kSlotPadding and don't
344 /// touch the slots at either end, to avoid false sharing
345 detail::SingleElementQueue<T,Atom>* slots_;
347 /// The number of slots_ indices that we advance for each ticket, to
348 /// avoid false sharing. Ideally slots_[i] and slots_[i + stride_]
349 /// aren't on the same cache line
352 /// Enqueuers get tickets from here
353 Atom<uint64_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING pushTicket_;
355 /// Dequeuers get tickets from here
356 Atom<uint64_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING popTicket_;
358 /// This is how many times we will spin before using FUTEX_WAIT when
359 /// the queue is full on enqueue, adaptively computed by occasionally
360 /// spinning for longer and smoothing with an exponential moving average
361 Atom<int> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING pushSpinCutoff_;
363 /// The adaptive spin cutoff when the queue is empty on dequeue
364 Atom<int> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING popSpinCutoff_;
366 /// Alignment doesn't prevent false sharing at the end of the struct,
367 /// so fill out the last cache line
368 char padding_[detail::CacheLocality::kFalseSharingRange - sizeof(Atom<int>)];
371 /// We assign tickets in increasing order, but we don't want to
372 /// access neighboring elements of slots_ because that will lead to
373 /// false sharing (multiple cores accessing the same cache line even
374 /// though they aren't accessing the same bytes in that cache line).
375 /// To avoid this we advance by stride slots per ticket.
377 /// We need gcd(capacity, stride) to be 1 so that we will use all
378 /// of the slots. We ensure this by only considering prime strides,
379 /// which either have no common divisors with capacity or else have
380 /// a zero remainder after dividing by capacity. That is sufficient
381 /// to guarantee correctness, but we also want to actually spread the
382 /// accesses away from each other to avoid false sharing (consider a
383 /// stride of 7 with a capacity of 8). To that end we try a few taking
384 /// care to observe that advancing by -1 is as bad as advancing by 1
385 /// when in comes to false sharing.
387 /// The simple way to avoid false sharing would be to pad each
388 /// SingleElementQueue, but since we have capacity_ of them that could
389 /// waste a lot of space.
390 static int computeStride(size_t capacity) noexcept {
391 static const int smallPrimes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };
395 for (int stride : smallPrimes) {
396 if ((stride % capacity) == 0 || (capacity % stride) == 0) {
399 size_t sep = stride % capacity;
400 sep = std::min(sep, capacity - sep);
409 /// Returns the index into slots_ that should be used when enqueuing or
410 /// dequeuing with the specified ticket
411 size_t idx(uint64_t ticket) noexcept {
412 return ((ticket * stride_) % capacity_) + kSlotPadding;
415 /// Maps an enqueue or dequeue ticket to the turn should be used at the
416 /// corresponding SingleElementQueue
417 uint32_t turn(uint64_t ticket) noexcept {
418 return ticket / capacity_;
421 /// Tries to obtain a push ticket for which SingleElementQueue::enqueue
422 /// won't block. Returns true on immediate success, false on immediate
424 bool tryObtainReadyPushTicket(uint64_t& rv) noexcept {
425 auto ticket = pushTicket_.load(std::memory_order_acquire); // A
427 if (!slots_[idx(ticket)].mayEnqueue(turn(ticket))) {
428 // if we call enqueue(ticket, ...) on the SingleElementQueue
429 // right now it would block, but this might no longer be the next
430 // ticket. We can increase the chance of tryEnqueue success under
431 // contention (without blocking) by rechecking the ticket dispenser
433 ticket = pushTicket_.load(std::memory_order_acquire); // B
434 if (prev == ticket) {
435 // mayEnqueue was bracketed by two reads (A or prev B or prev
436 // failing CAS to B), so we are definitely unable to enqueue
440 // we will bracket the mayEnqueue check with a read (A or prev B
441 // or prev failing CAS) and the following CAS. If the CAS fails
442 // it will effect a load of pushTicket_
443 if (pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
451 /// Tries to obtain a push ticket which can be satisfied if all
452 /// in-progress pops complete. This function does not block, but
453 /// blocking may be required when using the returned ticket if some
454 /// other thread's pop is still in progress (ticket has been granted but
455 /// pop has not yet completed).
456 bool tryObtainPromisedPushTicket(uint64_t& rv) noexcept {
457 auto numPushes = pushTicket_.load(std::memory_order_acquire); // A
459 auto numPops = popTicket_.load(std::memory_order_acquire); // B
460 // n will be negative if pops are pending
461 int64_t n = numPushes - numPops;
462 if (n >= static_cast<ssize_t>(capacity_)) {
463 // Full, linearize at B. We don't need to recheck the read we
464 // performed at A, because if numPushes was stale at B then the
465 // real numPushes value is even worse
468 if (pushTicket_.compare_exchange_strong(numPushes, numPushes + 1)) {
475 /// Tries to obtain a pop ticket for which SingleElementQueue::dequeue
476 /// won't block. Returns true on immediate success, false on immediate
478 bool tryObtainReadyPopTicket(uint64_t& rv) noexcept {
479 auto ticket = popTicket_.load(std::memory_order_acquire);
481 if (!slots_[idx(ticket)].mayDequeue(turn(ticket))) {
483 ticket = popTicket_.load(std::memory_order_acquire);
484 if (prev == ticket) {
488 if (popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
496 /// Similar to tryObtainReadyPopTicket, but returns a pop ticket whose
497 /// corresponding push ticket has already been handed out, rather than
498 /// returning one whose corresponding push ticket has already been
499 /// completed. This means that there is a possibility that the caller
500 /// will block when using the ticket, but it allows the user to rely on
501 /// the fact that if enqueue has succeeded, tryObtainPromisedPopTicket
502 /// will return true. The "try" part of this is that we won't have
503 /// to block waiting for someone to call enqueue, although we might
504 /// have to block waiting for them to finish executing code inside the
505 /// MPMCQueue itself.
506 bool tryObtainPromisedPopTicket(uint64_t& rv) noexcept {
507 auto numPops = popTicket_.load(std::memory_order_acquire); // A
509 auto numPushes = pushTicket_.load(std::memory_order_acquire); // B
510 if (numPops >= numPushes) {
511 // Empty, or empty with pending pops. Linearize at B. We don't
512 // need to recheck the read we performed at A, because if numPops
513 // is stale then the fresh value is larger and the >= is still true
516 if (popTicket_.compare_exchange_strong(numPops, numPops + 1)) {
523 // Given a ticket, constructs an enqueued item using args
524 template <typename ...Args>
525 void enqueueWithTicket(uint64_t ticket, Args&&... args) noexcept {
526 slots_[idx(ticket)].enqueue(turn(ticket),
528 (ticket % kAdaptationFreq) == 0,
529 std::forward<Args>(args)...);
532 // Given a ticket, dequeues the corresponding element
533 void dequeueWithTicket(uint64_t ticket, T& elem) noexcept {
534 slots_[idx(ticket)].dequeue(turn(ticket),
536 (ticket % kAdaptationFreq) == 0,
544 /// A TurnSequencer allows threads to order their execution according to
545 /// a monotonically increasing (with wraparound) "turn" value. The two
546 /// operations provided are to wait for turn T, and to move to the next
547 /// turn. Every thread that is waiting for T must have arrived before
548 /// that turn is marked completed (for MPMCQueue only one thread waits
549 /// for any particular turn, so this is trivially true).
551 /// TurnSequencer's state_ holds 26 bits of the current turn (shifted
552 /// left by 6), along with a 6 bit saturating value that records the
553 /// maximum waiter minus the current turn. Wraparound of the turn space
554 /// is expected and handled. This allows us to atomically adjust the
555 /// number of outstanding waiters when we perform a FUTEX_WAKE operation.
556 /// Compare this strategy to sem_t's separate num_waiters field, which
557 /// isn't decremented until after the waiting thread gets scheduled,
558 /// during which time more enqueues might have occurred and made pointless
559 /// FUTEX_WAKE calls.
561 /// TurnSequencer uses futex() directly. It is optimized for the
562 /// case that the highest awaited turn is 32 or less higher than the
563 /// current turn. We use the FUTEX_WAIT_BITSET variant, which lets
564 /// us embed 32 separate wakeup channels in a single futex. See
565 /// http://locklessinc.com/articles/futex_cheat_sheet for a description.
567 /// We only need to keep exact track of the delta between the current
568 /// turn and the maximum waiter for the 32 turns that follow the current
569 /// one, because waiters at turn t+32 will be awoken at turn t. At that
570 /// point they can then adjust the delta using the higher base. Since we
571 /// need to encode waiter deltas of 0 to 32 inclusive, we use 6 bits.
572 /// We actually store waiter deltas up to 63, since that might reduce
573 /// the number of CAS operations a tiny bit.
575 /// To avoid some futex() calls entirely, TurnSequencer uses an adaptive
576 /// spin cutoff before waiting. The overheads (and convergence rate)
577 /// of separately tracking the spin cutoff for each TurnSequencer would
578 /// be prohibitive, so the actual storage is passed in as a parameter and
579 /// updated atomically. This also lets the caller use different adaptive
580 /// cutoffs for different operations (read versus write, for example).
581 /// To avoid contention, the spin cutoff is only updated when requested
583 template <template<typename> class Atom>
584 struct TurnSequencer {
585 explicit TurnSequencer(const uint32_t firstTurn = 0) noexcept
586 : state_(encode(firstTurn << kTurnShift, 0))
589 /// Returns true iff a call to waitForTurn(turn, ...) won't block
590 bool isTurn(const uint32_t turn) const noexcept {
591 auto state = state_.load(std::memory_order_acquire);
592 return decodeCurrentSturn(state) == (turn << kTurnShift);
595 // Internally we always work with shifted turn values, which makes the
596 // truncation and wraparound work correctly. This leaves us bits at
597 // the bottom to store the number of waiters. We call shifted turns
598 // "sturns" inside this class.
600 /// Blocks the current thread until turn has arrived. If
601 /// updateSpinCutoff is true then this will spin for up to kMaxSpins tries
602 /// before blocking and will adjust spinCutoff based on the results,
603 /// otherwise it will spin for at most spinCutoff spins.
604 void waitForTurn(const uint32_t turn,
605 Atom<int>& spinCutoff,
606 const bool updateSpinCutoff) noexcept {
607 int prevThresh = spinCutoff.load(std::memory_order_relaxed);
608 const int effectiveSpinCutoff =
609 updateSpinCutoff || prevThresh == 0 ? kMaxSpins : prevThresh;
612 const uint32_t sturn = turn << kTurnShift;
613 for (tries = 0; ; ++tries) {
614 uint32_t state = state_.load(std::memory_order_acquire);
615 uint32_t current_sturn = decodeCurrentSturn(state);
616 if (current_sturn == sturn) {
620 // wrap-safe version of assert(current_sturn < sturn)
621 assert(sturn - current_sturn < std::numeric_limits<uint32_t>::max() / 2);
623 // the first effectSpinCutoff tries are spins, after that we will
624 // record ourself as a waiter and block with futexWait
625 if (tries < effectiveSpinCutoff) {
626 asm volatile ("pause");
630 uint32_t current_max_waiter_delta = decodeMaxWaitersDelta(state);
631 uint32_t our_waiter_delta = (sturn - current_sturn) >> kTurnShift;
633 if (our_waiter_delta <= current_max_waiter_delta) {
634 // state already records us as waiters, probably because this
635 // isn't our first time around this loop
638 new_state = encode(current_sturn, our_waiter_delta);
639 if (state != new_state &&
640 !state_.compare_exchange_strong(state, new_state)) {
644 state_.futexWait(new_state, futexChannel(turn));
647 if (updateSpinCutoff || prevThresh == 0) {
648 // if we hit kMaxSpins then spinning was pointless, so the right
649 // spinCutoff is kMinSpins
651 if (tries >= kMaxSpins) {
654 // to account for variations, we allow ourself to spin 2*N when
655 // we think that N is actually required in order to succeed
656 target = std::min(int{kMaxSpins}, std::max(int{kMinSpins}, tries * 2));
659 if (prevThresh == 0) {
661 spinCutoff.store(target);
663 // try once, keep moving if CAS fails. Exponential moving average
665 spinCutoff.compare_exchange_weak(
666 prevThresh, prevThresh + (target - prevThresh) / 8);
671 /// Unblocks a thread running waitForTurn(turn + 1)
672 void completeTurn(const uint32_t turn) noexcept {
673 uint32_t state = state_.load(std::memory_order_acquire);
675 assert(state == encode(turn << kTurnShift, decodeMaxWaitersDelta(state)));
676 uint32_t max_waiter_delta = decodeMaxWaitersDelta(state);
677 uint32_t new_state = encode(
678 (turn + 1) << kTurnShift,
679 max_waiter_delta == 0 ? 0 : max_waiter_delta - 1);
680 if (state_.compare_exchange_strong(state, new_state)) {
681 if (max_waiter_delta != 0) {
682 state_.futexWake(std::numeric_limits<int>::max(),
683 futexChannel(turn + 1));
687 // failing compare_exchange_strong updates first arg to the value
688 // that caused the failure, so no need to reread state_
692 /// Returns the least-most significant byte of the current uncompleted
693 /// turn. The full 32 bit turn cannot be recovered.
694 uint8_t uncompletedTurnLSB() const noexcept {
695 return state_.load(std::memory_order_acquire) >> kTurnShift;
700 /// kTurnShift counts the bits that are stolen to record the delta
701 /// between the current turn and the maximum waiter. It needs to be big
702 /// enough to record wait deltas of 0 to 32 inclusive. Waiters more
703 /// than 32 in the future will be woken up 32*n turns early (since
704 /// their BITSET will hit) and will adjust the waiter count again.
705 /// We go a bit beyond and let the waiter count go up to 63, which
706 /// is free and might save us a few CAS
708 kWaitersMask = (1 << kTurnShift) - 1,
710 /// The minimum spin count that we will adaptively select
713 /// The maximum spin count that we will adaptively select, and the
714 /// spin count that will be used when probing to get a new data point
715 /// for the adaptation
719 /// This holds both the current turn, and the highest waiting turn,
720 /// stored as (current_turn << 6) | min(63, max(waited_turn - current_turn))
723 /// Returns the bitmask to pass futexWait or futexWake when communicating
724 /// about the specified turn
725 int futexChannel(uint32_t turn) const noexcept {
726 return 1 << (turn & 31);
729 uint32_t decodeCurrentSturn(uint32_t state) const noexcept {
730 return state & ~kWaitersMask;
733 uint32_t decodeMaxWaitersDelta(uint32_t state) const noexcept {
734 return state & kWaitersMask;
737 uint32_t encode(uint32_t currentSturn, uint32_t maxWaiterD) const noexcept {
738 return currentSturn | std::min(uint32_t{ kWaitersMask }, maxWaiterD);
743 /// SingleElementQueue implements a blocking queue that holds at most one
744 /// item, and that requires its users to assign incrementing identifiers
745 /// (turns) to each enqueue and dequeue operation. Note that the turns
746 /// used by SingleElementQueue are doubled inside the TurnSequencer
747 template <typename T, template <typename> class Atom>
748 struct SingleElementQueue {
750 ~SingleElementQueue() noexcept {
751 if ((sequencer_.uncompletedTurnLSB() & 1) == 1) {
752 // we are pending a dequeue, so we have a constructed item
757 /// enqueue using in-place noexcept construction
758 template <typename ...Args,
759 typename = typename std::enable_if<
760 std::is_nothrow_constructible<T,Args...>::value>::type>
761 void enqueue(const uint32_t turn,
762 Atom<int>& spinCutoff,
763 const bool updateSpinCutoff,
764 Args&&... args) noexcept {
765 sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
766 new (&contents_) T(std::forward<Args>(args)...);
767 sequencer_.completeTurn(turn * 2);
770 /// enqueue using move construction, either real (if
771 /// is_nothrow_move_constructible) or simulated using relocation and
772 /// default construction (if IsRelocatable and has_nothrow_constructor)
773 template <typename = typename std::enable_if<
774 (folly::IsRelocatable<T>::value &&
775 boost::has_nothrow_constructor<T>::value) ||
776 std::is_nothrow_constructible<T,T&&>::value>::type>
777 void enqueue(const uint32_t turn,
778 Atom<int>& spinCutoff,
779 const bool updateSpinCutoff,
780 T&& goner) noexcept {
781 if (std::is_nothrow_constructible<T,T&&>::value) {
783 sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
784 new (&contents_) T(std::move(goner));
785 sequencer_.completeTurn(turn * 2);
787 // simulate nothrow move with relocation, followed by default
788 // construction to fill the gap we created
789 sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
790 memcpy(&contents_, &goner, sizeof(T));
791 sequencer_.completeTurn(turn * 2);
796 bool mayEnqueue(const uint32_t turn) const noexcept {
797 return sequencer_.isTurn(turn * 2);
800 void dequeue(uint32_t turn,
801 Atom<int>& spinCutoff,
802 const bool updateSpinCutoff,
804 if (folly::IsRelocatable<T>::value) {
805 // this version is preferred, because we do as much work as possible
810 // unlikely, but if we don't complete our turn the queue will die
812 sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
813 memcpy(&elem, &contents_, sizeof(T));
814 sequencer_.completeTurn(turn * 2 + 1);
816 // use nothrow move assignment
817 sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
818 elem = std::move(*ptr());
820 sequencer_.completeTurn(turn * 2 + 1);
824 bool mayDequeue(const uint32_t turn) const noexcept {
825 return sequencer_.isTurn(turn * 2 + 1);
829 /// Storage for a T constructed with placement new
830 typename std::aligned_storage<sizeof(T),alignof(T)>::type contents_;
832 /// Even turns are pushes, odd turns are pops
833 TurnSequencer<Atom> sequencer_;
836 return static_cast<T*>(static_cast<void*>(&contents_));
839 void destroyContents() noexcept {
843 // g++ doesn't seem to have std::is_nothrow_destructible yet
846 memset(&contents_, 'Q', sizeof(T));
851 } // namespace detail