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<uint32_t> FOLLY_ALIGN_TO_AVOID_FALSE_SHARING pushSpinCutoff_;
363 /// The adaptive spin cutoff when the queue is empty on dequeue
364 Atom<uint32_t> 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 -
369 sizeof(Atom<uint32_t>)];
372 /// We assign tickets in increasing order, but we don't want to
373 /// access neighboring elements of slots_ because that will lead to
374 /// false sharing (multiple cores accessing the same cache line even
375 /// though they aren't accessing the same bytes in that cache line).
376 /// To avoid this we advance by stride slots per ticket.
378 /// We need gcd(capacity, stride) to be 1 so that we will use all
379 /// of the slots. We ensure this by only considering prime strides,
380 /// which either have no common divisors with capacity or else have
381 /// a zero remainder after dividing by capacity. That is sufficient
382 /// to guarantee correctness, but we also want to actually spread the
383 /// accesses away from each other to avoid false sharing (consider a
384 /// stride of 7 with a capacity of 8). To that end we try a few taking
385 /// care to observe that advancing by -1 is as bad as advancing by 1
386 /// when in comes to false sharing.
388 /// The simple way to avoid false sharing would be to pad each
389 /// SingleElementQueue, but since we have capacity_ of them that could
390 /// waste a lot of space.
391 static int computeStride(size_t capacity) noexcept {
392 static const int smallPrimes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };
396 for (int stride : smallPrimes) {
397 if ((stride % capacity) == 0 || (capacity % stride) == 0) {
400 size_t sep = stride % capacity;
401 sep = std::min(sep, capacity - sep);
410 /// Returns the index into slots_ that should be used when enqueuing or
411 /// dequeuing with the specified ticket
412 size_t idx(uint64_t ticket) noexcept {
413 return ((ticket * stride_) % capacity_) + kSlotPadding;
416 /// Maps an enqueue or dequeue ticket to the turn should be used at the
417 /// corresponding SingleElementQueue
418 uint32_t turn(uint64_t ticket) noexcept {
419 return ticket / capacity_;
422 /// Tries to obtain a push ticket for which SingleElementQueue::enqueue
423 /// won't block. Returns true on immediate success, false on immediate
425 bool tryObtainReadyPushTicket(uint64_t& rv) noexcept {
426 auto ticket = pushTicket_.load(std::memory_order_acquire); // A
428 if (!slots_[idx(ticket)].mayEnqueue(turn(ticket))) {
429 // if we call enqueue(ticket, ...) on the SingleElementQueue
430 // right now it would block, but this might no longer be the next
431 // ticket. We can increase the chance of tryEnqueue success under
432 // contention (without blocking) by rechecking the ticket dispenser
434 ticket = pushTicket_.load(std::memory_order_acquire); // B
435 if (prev == ticket) {
436 // mayEnqueue was bracketed by two reads (A or prev B or prev
437 // failing CAS to B), so we are definitely unable to enqueue
441 // we will bracket the mayEnqueue check with a read (A or prev B
442 // or prev failing CAS) and the following CAS. If the CAS fails
443 // it will effect a load of pushTicket_
444 if (pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
452 /// Tries to obtain a push ticket which can be satisfied if all
453 /// in-progress pops complete. This function does not block, but
454 /// blocking may be required when using the returned ticket if some
455 /// other thread's pop is still in progress (ticket has been granted but
456 /// pop has not yet completed).
457 bool tryObtainPromisedPushTicket(uint64_t& rv) noexcept {
458 auto numPushes = pushTicket_.load(std::memory_order_acquire); // A
460 auto numPops = popTicket_.load(std::memory_order_acquire); // B
461 // n will be negative if pops are pending
462 int64_t n = numPushes - numPops;
463 if (n >= static_cast<ssize_t>(capacity_)) {
464 // Full, linearize at B. We don't need to recheck the read we
465 // performed at A, because if numPushes was stale at B then the
466 // real numPushes value is even worse
469 if (pushTicket_.compare_exchange_strong(numPushes, numPushes + 1)) {
476 /// Tries to obtain a pop ticket for which SingleElementQueue::dequeue
477 /// won't block. Returns true on immediate success, false on immediate
479 bool tryObtainReadyPopTicket(uint64_t& rv) noexcept {
480 auto ticket = popTicket_.load(std::memory_order_acquire);
482 if (!slots_[idx(ticket)].mayDequeue(turn(ticket))) {
484 ticket = popTicket_.load(std::memory_order_acquire);
485 if (prev == ticket) {
489 if (popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
497 /// Similar to tryObtainReadyPopTicket, but returns a pop ticket whose
498 /// corresponding push ticket has already been handed out, rather than
499 /// returning one whose corresponding push ticket has already been
500 /// completed. This means that there is a possibility that the caller
501 /// will block when using the ticket, but it allows the user to rely on
502 /// the fact that if enqueue has succeeded, tryObtainPromisedPopTicket
503 /// will return true. The "try" part of this is that we won't have
504 /// to block waiting for someone to call enqueue, although we might
505 /// have to block waiting for them to finish executing code inside the
506 /// MPMCQueue itself.
507 bool tryObtainPromisedPopTicket(uint64_t& rv) noexcept {
508 auto numPops = popTicket_.load(std::memory_order_acquire); // A
510 auto numPushes = pushTicket_.load(std::memory_order_acquire); // B
511 if (numPops >= numPushes) {
512 // Empty, or empty with pending pops. Linearize at B. We don't
513 // need to recheck the read we performed at A, because if numPops
514 // is stale then the fresh value is larger and the >= is still true
517 if (popTicket_.compare_exchange_strong(numPops, numPops + 1)) {
524 // Given a ticket, constructs an enqueued item using args
525 template <typename ...Args>
526 void enqueueWithTicket(uint64_t ticket, Args&&... args) noexcept {
527 slots_[idx(ticket)].enqueue(turn(ticket),
529 (ticket % kAdaptationFreq) == 0,
530 std::forward<Args>(args)...);
533 // Given a ticket, dequeues the corresponding element
534 void dequeueWithTicket(uint64_t ticket, T& elem) noexcept {
535 slots_[idx(ticket)].dequeue(turn(ticket),
537 (ticket % kAdaptationFreq) == 0,
545 /// A TurnSequencer allows threads to order their execution according to
546 /// a monotonically increasing (with wraparound) "turn" value. The two
547 /// operations provided are to wait for turn T, and to move to the next
548 /// turn. Every thread that is waiting for T must have arrived before
549 /// that turn is marked completed (for MPMCQueue only one thread waits
550 /// for any particular turn, so this is trivially true).
552 /// TurnSequencer's state_ holds 26 bits of the current turn (shifted
553 /// left by 6), along with a 6 bit saturating value that records the
554 /// maximum waiter minus the current turn. Wraparound of the turn space
555 /// is expected and handled. This allows us to atomically adjust the
556 /// number of outstanding waiters when we perform a FUTEX_WAKE operation.
557 /// Compare this strategy to sem_t's separate num_waiters field, which
558 /// isn't decremented until after the waiting thread gets scheduled,
559 /// during which time more enqueues might have occurred and made pointless
560 /// FUTEX_WAKE calls.
562 /// TurnSequencer uses futex() directly. It is optimized for the
563 /// case that the highest awaited turn is 32 or less higher than the
564 /// current turn. We use the FUTEX_WAIT_BITSET variant, which lets
565 /// us embed 32 separate wakeup channels in a single futex. See
566 /// http://locklessinc.com/articles/futex_cheat_sheet for a description.
568 /// We only need to keep exact track of the delta between the current
569 /// turn and the maximum waiter for the 32 turns that follow the current
570 /// one, because waiters at turn t+32 will be awoken at turn t. At that
571 /// point they can then adjust the delta using the higher base. Since we
572 /// need to encode waiter deltas of 0 to 32 inclusive, we use 6 bits.
573 /// We actually store waiter deltas up to 63, since that might reduce
574 /// the number of CAS operations a tiny bit.
576 /// To avoid some futex() calls entirely, TurnSequencer uses an adaptive
577 /// spin cutoff before waiting. The overheads (and convergence rate)
578 /// of separately tracking the spin cutoff for each TurnSequencer would
579 /// be prohibitive, so the actual storage is passed in as a parameter and
580 /// updated atomically. This also lets the caller use different adaptive
581 /// cutoffs for different operations (read versus write, for example).
582 /// To avoid contention, the spin cutoff is only updated when requested
584 template <template<typename> class Atom>
585 struct TurnSequencer {
586 explicit TurnSequencer(const uint32_t firstTurn = 0) noexcept
587 : state_(encode(firstTurn << kTurnShift, 0))
590 /// Returns true iff a call to waitForTurn(turn, ...) won't block
591 bool isTurn(const uint32_t turn) const noexcept {
592 auto state = state_.load(std::memory_order_acquire);
593 return decodeCurrentSturn(state) == (turn << kTurnShift);
596 // Internally we always work with shifted turn values, which makes the
597 // truncation and wraparound work correctly. This leaves us bits at
598 // the bottom to store the number of waiters. We call shifted turns
599 // "sturns" inside this class.
601 /// Blocks the current thread until turn has arrived. If
602 /// updateSpinCutoff is true then this will spin for up to kMaxSpins tries
603 /// before blocking and will adjust spinCutoff based on the results,
604 /// otherwise it will spin for at most spinCutoff spins.
605 void waitForTurn(const uint32_t turn,
606 Atom<uint32_t>& spinCutoff,
607 const bool updateSpinCutoff) noexcept {
608 uint32_t prevThresh = spinCutoff.load(std::memory_order_relaxed);
609 const uint32_t effectiveSpinCutoff =
610 updateSpinCutoff || prevThresh == 0 ? kMaxSpins : prevThresh;
613 const uint32_t sturn = turn << kTurnShift;
614 for (tries = 0; ; ++tries) {
615 uint32_t state = state_.load(std::memory_order_acquire);
616 uint32_t current_sturn = decodeCurrentSturn(state);
617 if (current_sturn == sturn) {
621 // wrap-safe version of assert(current_sturn < sturn)
622 assert(sturn - current_sturn < std::numeric_limits<uint32_t>::max() / 2);
624 // the first effectSpinCutoff tries are spins, after that we will
625 // record ourself as a waiter and block with futexWait
626 if (tries < effectiveSpinCutoff) {
627 asm volatile ("pause");
631 uint32_t current_max_waiter_delta = decodeMaxWaitersDelta(state);
632 uint32_t our_waiter_delta = (sturn - current_sturn) >> kTurnShift;
634 if (our_waiter_delta <= current_max_waiter_delta) {
635 // state already records us as waiters, probably because this
636 // isn't our first time around this loop
639 new_state = encode(current_sturn, our_waiter_delta);
640 if (state != new_state &&
641 !state_.compare_exchange_strong(state, new_state)) {
645 state_.futexWait(new_state, futexChannel(turn));
648 if (updateSpinCutoff || prevThresh == 0) {
649 // if we hit kMaxSpins then spinning was pointless, so the right
650 // spinCutoff is kMinSpins
652 if (tries >= kMaxSpins) {
655 // to account for variations, we allow ourself to spin 2*N when
656 // we think that N is actually required in order to succeed
657 target = std::min<uint32_t>(kMaxSpins,
658 std::max<uint32_t>(kMinSpins, tries * 2));
661 if (prevThresh == 0) {
663 spinCutoff.store(target);
665 // try once, keep moving if CAS fails. Exponential moving average
667 spinCutoff.compare_exchange_weak(
668 prevThresh, prevThresh + (target - prevThresh) / 8);
673 /// Unblocks a thread running waitForTurn(turn + 1)
674 void completeTurn(const uint32_t turn) noexcept {
675 uint32_t state = state_.load(std::memory_order_acquire);
677 assert(state == encode(turn << kTurnShift, decodeMaxWaitersDelta(state)));
678 uint32_t max_waiter_delta = decodeMaxWaitersDelta(state);
679 uint32_t new_state = encode(
680 (turn + 1) << kTurnShift,
681 max_waiter_delta == 0 ? 0 : max_waiter_delta - 1);
682 if (state_.compare_exchange_strong(state, new_state)) {
683 if (max_waiter_delta != 0) {
684 state_.futexWake(std::numeric_limits<int>::max(),
685 futexChannel(turn + 1));
689 // failing compare_exchange_strong updates first arg to the value
690 // that caused the failure, so no need to reread state_
694 /// Returns the least-most significant byte of the current uncompleted
695 /// turn. The full 32 bit turn cannot be recovered.
696 uint8_t uncompletedTurnLSB() const noexcept {
697 return state_.load(std::memory_order_acquire) >> kTurnShift;
702 /// kTurnShift counts the bits that are stolen to record the delta
703 /// between the current turn and the maximum waiter. It needs to be big
704 /// enough to record wait deltas of 0 to 32 inclusive. Waiters more
705 /// than 32 in the future will be woken up 32*n turns early (since
706 /// their BITSET will hit) and will adjust the waiter count again.
707 /// We go a bit beyond and let the waiter count go up to 63, which
708 /// is free and might save us a few CAS
710 kWaitersMask = (1 << kTurnShift) - 1,
712 /// The minimum spin count that we will adaptively select
715 /// The maximum spin count that we will adaptively select, and the
716 /// spin count that will be used when probing to get a new data point
717 /// for the adaptation
721 /// This holds both the current turn, and the highest waiting turn,
722 /// stored as (current_turn << 6) | min(63, max(waited_turn - current_turn))
725 /// Returns the bitmask to pass futexWait or futexWake when communicating
726 /// about the specified turn
727 int futexChannel(uint32_t turn) const noexcept {
728 return 1 << (turn & 31);
731 uint32_t decodeCurrentSturn(uint32_t state) const noexcept {
732 return state & ~kWaitersMask;
735 uint32_t decodeMaxWaitersDelta(uint32_t state) const noexcept {
736 return state & kWaitersMask;
739 uint32_t encode(uint32_t currentSturn, uint32_t maxWaiterD) const noexcept {
740 return currentSturn | std::min(uint32_t{ kWaitersMask }, maxWaiterD);
745 /// SingleElementQueue implements a blocking queue that holds at most one
746 /// item, and that requires its users to assign incrementing identifiers
747 /// (turns) to each enqueue and dequeue operation. Note that the turns
748 /// used by SingleElementQueue are doubled inside the TurnSequencer
749 template <typename T, template <typename> class Atom>
750 struct SingleElementQueue {
752 ~SingleElementQueue() noexcept {
753 if ((sequencer_.uncompletedTurnLSB() & 1) == 1) {
754 // we are pending a dequeue, so we have a constructed item
759 /// enqueue using in-place noexcept construction
760 template <typename ...Args,
761 typename = typename std::enable_if<
762 std::is_nothrow_constructible<T,Args...>::value>::type>
763 void enqueue(const uint32_t turn,
764 Atom<uint32_t>& spinCutoff,
765 const bool updateSpinCutoff,
766 Args&&... args) noexcept {
767 sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
768 new (&contents_) T(std::forward<Args>(args)...);
769 sequencer_.completeTurn(turn * 2);
772 /// enqueue using move construction, either real (if
773 /// is_nothrow_move_constructible) or simulated using relocation and
774 /// default construction (if IsRelocatable and has_nothrow_constructor)
775 template <typename = typename std::enable_if<
776 (folly::IsRelocatable<T>::value &&
777 boost::has_nothrow_constructor<T>::value) ||
778 std::is_nothrow_constructible<T,T&&>::value>::type>
779 void enqueue(const uint32_t turn,
780 Atom<uint32_t>& spinCutoff,
781 const bool updateSpinCutoff,
782 T&& goner) noexcept {
783 if (std::is_nothrow_constructible<T,T&&>::value) {
785 sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
786 new (&contents_) T(std::move(goner));
787 sequencer_.completeTurn(turn * 2);
789 // simulate nothrow move with relocation, followed by default
790 // construction to fill the gap we created
791 sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
792 memcpy(&contents_, &goner, sizeof(T));
793 sequencer_.completeTurn(turn * 2);
798 bool mayEnqueue(const uint32_t turn) const noexcept {
799 return sequencer_.isTurn(turn * 2);
802 void dequeue(uint32_t turn,
803 Atom<uint32_t>& spinCutoff,
804 const bool updateSpinCutoff,
806 if (folly::IsRelocatable<T>::value) {
807 // this version is preferred, because we do as much work as possible
812 // unlikely, but if we don't complete our turn the queue will die
814 sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
815 memcpy(&elem, &contents_, sizeof(T));
816 sequencer_.completeTurn(turn * 2 + 1);
818 // use nothrow move assignment
819 sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
820 elem = std::move(*ptr());
822 sequencer_.completeTurn(turn * 2 + 1);
826 bool mayDequeue(const uint32_t turn) const noexcept {
827 return sequencer_.isTurn(turn * 2 + 1);
831 /// Storage for a T constructed with placement new
832 typename std::aligned_storage<sizeof(T),alignof(T)>::type contents_;
834 /// Even turns are pushes, odd turns are pops
835 TurnSequencer<Atom> sequencer_;
838 return static_cast<T*>(static_cast<void*>(&contents_));
841 void destroyContents() noexcept {
845 // g++ doesn't seem to have std::is_nothrow_destructible yet
848 memset(&contents_, 'Q', sizeof(T));
853 } // namespace detail