MPMCQueue.h 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514
  1. /*
  2. * Copyright 2013-present Facebook, Inc.
  3. *
  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
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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.
  15. */
  16. #pragma once
  17. #include <algorithm>
  18. #include <atomic>
  19. #include <cassert>
  20. #include <cstring>
  21. #include <limits>
  22. #include <type_traits>
  23. #include <boost/noncopyable.hpp>
  24. #include <folly/Traits.h>
  25. #include <folly/concurrency/CacheLocality.h>
  26. #include <folly/detail/TurnSequencer.h>
  27. #include <folly/portability/Unistd.h>
  28. namespace folly {
  29. namespace detail {
  30. template <typename T, template <typename> class Atom>
  31. struct SingleElementQueue;
  32. template <typename T>
  33. class MPMCPipelineStageImpl;
  34. /// MPMCQueue base CRTP template
  35. template <typename>
  36. class MPMCQueueBase;
  37. } // namespace detail
  38. /// MPMCQueue<T> is a high-performance bounded concurrent queue that
  39. /// supports multiple producers, multiple consumers, and optional blocking.
  40. /// The queue has a fixed capacity, for which all memory will be allocated
  41. /// up front. The bulk of the work of enqueuing and dequeuing can be
  42. /// performed in parallel.
  43. ///
  44. /// MPMCQueue is linearizable. That means that if a call to write(A)
  45. /// returns before a call to write(B) begins, then A will definitely end up
  46. /// in the queue before B, and if a call to read(X) returns before a call
  47. /// to read(Y) is started, that X will be something from earlier in the
  48. /// queue than Y. This also means that if a read call returns a value, you
  49. /// can be sure that all previous elements of the queue have been assigned
  50. /// a reader (that reader might not yet have returned, but it exists).
  51. ///
  52. /// The underlying implementation uses a ticket dispenser for the head and
  53. /// the tail, spreading accesses across N single-element queues to produce
  54. /// a queue with capacity N. The ticket dispensers use atomic increment,
  55. /// which is more robust to contention than a CAS loop. Each of the
  56. /// single-element queues uses its own CAS to serialize access, with an
  57. /// adaptive spin cutoff. When spinning fails on a single-element queue
  58. /// it uses futex()'s _BITSET operations to reduce unnecessary wakeups
  59. /// even if multiple waiters are present on an individual queue (such as
  60. /// when the MPMCQueue's capacity is smaller than the number of enqueuers
  61. /// or dequeuers).
  62. ///
  63. /// In benchmarks (contained in tao/queues/ConcurrentQueueTests)
  64. /// it handles 1 to 1, 1 to N, N to 1, and N to M thread counts better
  65. /// than any of the alternatives present in fbcode, for both small (~10)
  66. /// and large capacities. In these benchmarks it is also faster than
  67. /// tbb::concurrent_bounded_queue for all configurations. When there are
  68. /// many more threads than cores, MPMCQueue is _much_ faster than the tbb
  69. /// queue because it uses futex() to block and unblock waiting threads,
  70. /// rather than spinning with sched_yield.
  71. ///
  72. /// NOEXCEPT INTERACTION: tl;dr; If it compiles you're fine. Ticket-based
  73. /// queues separate the assignment of queue positions from the actual
  74. /// construction of the in-queue elements, which means that the T
  75. /// constructor used during enqueue must not throw an exception. This is
  76. /// enforced at compile time using type traits, which requires that T be
  77. /// adorned with accurate noexcept information. If your type does not
  78. /// use noexcept, you will have to wrap it in something that provides
  79. /// the guarantee. We provide an alternate safe implementation for types
  80. /// that don't use noexcept but that are marked folly::IsRelocatable
  81. /// and std::is_nothrow_constructible, which is common for folly types.
  82. /// In particular, if you can declare FOLLY_ASSUME_FBVECTOR_COMPATIBLE
  83. /// then your type can be put in MPMCQueue.
  84. ///
  85. /// If you have a pool of N queue consumers that you want to shut down
  86. /// after the queue has drained, one way is to enqueue N sentinel values
  87. /// to the queue. If the producer doesn't know how many consumers there
  88. /// are you can enqueue one sentinel and then have each consumer requeue
  89. /// two sentinels after it receives it (by requeuing 2 the shutdown can
  90. /// complete in O(log P) time instead of O(P)).
  91. template <
  92. typename T,
  93. template <typename> class Atom = std::atomic,
  94. bool Dynamic = false>
  95. class MPMCQueue : public detail::MPMCQueueBase<MPMCQueue<T, Atom, Dynamic>> {
  96. friend class detail::MPMCPipelineStageImpl<T>;
  97. using Slot = detail::SingleElementQueue<T, Atom>;
  98. public:
  99. explicit MPMCQueue(size_t queueCapacity)
  100. : detail::MPMCQueueBase<MPMCQueue<T, Atom, Dynamic>>(queueCapacity) {
  101. this->stride_ = this->computeStride(queueCapacity);
  102. this->slots_ = new Slot[queueCapacity + 2 * this->kSlotPadding];
  103. }
  104. MPMCQueue() noexcept {}
  105. };
  106. /// The dynamic version of MPMCQueue allows dynamic expansion of queue
  107. /// capacity, such that a queue may start with a smaller capacity than
  108. /// specified and expand only if needed. Users may optionally specify
  109. /// the initial capacity and the expansion multiplier.
  110. ///
  111. /// The design uses a seqlock to enforce mutual exclusion among
  112. /// expansion attempts. Regular operations read up-to-date queue
  113. /// information (slots array, capacity, stride) inside read-only
  114. /// seqlock sections, which are unimpeded when no expansion is in
  115. /// progress.
  116. ///
  117. /// An expansion computes a new capacity, allocates a new slots array,
  118. /// and updates stride. No information needs to be copied from the
  119. /// current slots array to the new one. When this happens, new slots
  120. /// will not have sequence numbers that match ticket numbers. The
  121. /// expansion needs to compute a ticket offset such that operations
  122. /// that use new arrays can adjust the calculations of slot indexes
  123. /// and sequence numbers that take into account that the new slots
  124. /// start with sequence numbers of zero. The current ticket offset is
  125. /// packed with the seqlock in an atomic 64-bit integer. The initial
  126. /// offset is zero.
  127. ///
  128. /// Lagging write and read operations with tickets lower than the
  129. /// ticket offset of the current slots array (i.e., the minimum ticket
  130. /// number that can be served by the current array) must use earlier
  131. /// closed arrays instead of the current one. Information about closed
  132. /// slots arrays (array address, capacity, stride, and offset) is
  133. /// maintained in a logarithmic-sized structure. Each entry in that
  134. /// structure never needs to be changed once set. The number of closed
  135. /// arrays is half the value of the seqlock (when unlocked).
  136. ///
  137. /// The acquisition of the seqlock to perform an expansion does not
  138. /// prevent the issuing of new push and pop tickets concurrently. The
  139. /// expansion must set the new ticket offset to a value that couldn't
  140. /// have been issued to an operation that has already gone through a
  141. /// seqlock read-only section (and hence obtained information for
  142. /// older closed arrays).
  143. ///
  144. /// Note that the total queue capacity can temporarily exceed the
  145. /// specified capacity when there are lagging consumers that haven't
  146. /// yet consumed all the elements in closed arrays. Users should not
  147. /// rely on the capacity of dynamic queues for synchronization, e.g.,
  148. /// they should not expect that a thread will definitely block on a
  149. /// call to blockingWrite() when the queue size is known to be equal
  150. /// to its capacity.
  151. ///
  152. /// Note that some writeIfNotFull() and tryWriteUntil() operations may
  153. /// fail even if the size of the queue is less than its maximum
  154. /// capacity and despite the success of expansion, if the operation
  155. /// happens to acquire a ticket that belongs to a closed array. This
  156. /// is a transient condition. Typically, one or two ticket values may
  157. /// be subject to such condition per expansion.
  158. ///
  159. /// The dynamic version is a partial specialization of MPMCQueue with
  160. /// Dynamic == true
  161. template <typename T, template <typename> class Atom>
  162. class MPMCQueue<T, Atom, true>
  163. : public detail::MPMCQueueBase<MPMCQueue<T, Atom, true>> {
  164. friend class detail::MPMCQueueBase<MPMCQueue<T, Atom, true>>;
  165. using Slot = detail::SingleElementQueue<T, Atom>;
  166. struct ClosedArray {
  167. uint64_t offset_{0};
  168. Slot* slots_{nullptr};
  169. size_t capacity_{0};
  170. int stride_{0};
  171. };
  172. public:
  173. explicit MPMCQueue(size_t queueCapacity)
  174. : detail::MPMCQueueBase<MPMCQueue<T, Atom, true>>(queueCapacity) {
  175. size_t cap = std::min<size_t>(kDefaultMinDynamicCapacity, queueCapacity);
  176. initQueue(cap, kDefaultExpansionMultiplier);
  177. }
  178. explicit MPMCQueue(
  179. size_t queueCapacity,
  180. size_t minCapacity,
  181. size_t expansionMultiplier)
  182. : detail::MPMCQueueBase<MPMCQueue<T, Atom, true>>(queueCapacity) {
  183. minCapacity = std::max<size_t>(1, minCapacity);
  184. size_t cap = std::min<size_t>(minCapacity, queueCapacity);
  185. expansionMultiplier = std::max<size_t>(2, expansionMultiplier);
  186. initQueue(cap, expansionMultiplier);
  187. }
  188. MPMCQueue() noexcept {
  189. dmult_ = 0;
  190. closed_ = nullptr;
  191. }
  192. MPMCQueue(MPMCQueue<T, Atom, true>&& rhs) noexcept {
  193. this->capacity_ = rhs.capacity_;
  194. this->slots_ = rhs.slots_;
  195. this->stride_ = rhs.stride_;
  196. this->dstate_.store(
  197. rhs.dstate_.load(std::memory_order_relaxed), std::memory_order_relaxed);
  198. this->dcapacity_.store(
  199. rhs.dcapacity_.load(std::memory_order_relaxed),
  200. std::memory_order_relaxed);
  201. this->pushTicket_.store(
  202. rhs.pushTicket_.load(std::memory_order_relaxed),
  203. std::memory_order_relaxed);
  204. this->popTicket_.store(
  205. rhs.popTicket_.load(std::memory_order_relaxed),
  206. std::memory_order_relaxed);
  207. this->pushSpinCutoff_.store(
  208. rhs.pushSpinCutoff_.load(std::memory_order_relaxed),
  209. std::memory_order_relaxed);
  210. this->popSpinCutoff_.store(
  211. rhs.popSpinCutoff_.load(std::memory_order_relaxed),
  212. std::memory_order_relaxed);
  213. dmult_ = rhs.dmult_;
  214. closed_ = rhs.closed_;
  215. rhs.capacity_ = 0;
  216. rhs.slots_ = nullptr;
  217. rhs.stride_ = 0;
  218. rhs.dstate_.store(0, std::memory_order_relaxed);
  219. rhs.dcapacity_.store(0, std::memory_order_relaxed);
  220. rhs.pushTicket_.store(0, std::memory_order_relaxed);
  221. rhs.popTicket_.store(0, std::memory_order_relaxed);
  222. rhs.pushSpinCutoff_.store(0, std::memory_order_relaxed);
  223. rhs.popSpinCutoff_.store(0, std::memory_order_relaxed);
  224. rhs.dmult_ = 0;
  225. rhs.closed_ = nullptr;
  226. }
  227. MPMCQueue<T, Atom, true> const& operator=(MPMCQueue<T, Atom, true>&& rhs) {
  228. if (this != &rhs) {
  229. this->~MPMCQueue();
  230. new (this) MPMCQueue(std::move(rhs));
  231. }
  232. return *this;
  233. }
  234. ~MPMCQueue() {
  235. if (closed_ != nullptr) {
  236. for (int i = getNumClosed(this->dstate_.load()) - 1; i >= 0; --i) {
  237. delete[] closed_[i].slots_;
  238. }
  239. delete[] closed_;
  240. }
  241. }
  242. size_t allocatedCapacity() const noexcept {
  243. return this->dcapacity_.load(std::memory_order_relaxed);
  244. }
  245. template <typename... Args>
  246. void blockingWrite(Args&&... args) noexcept {
  247. uint64_t ticket = this->pushTicket_++;
  248. Slot* slots;
  249. size_t cap;
  250. int stride;
  251. uint64_t state;
  252. uint64_t offset;
  253. do {
  254. if (!trySeqlockReadSection(state, slots, cap, stride)) {
  255. asm_volatile_pause();
  256. continue;
  257. }
  258. if (maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride)) {
  259. // There was an expansion after this ticket was issued.
  260. break;
  261. }
  262. if (slots[this->idx((ticket - offset), cap, stride)].mayEnqueue(
  263. this->turn(ticket - offset, cap))) {
  264. // A slot is ready. No need to expand.
  265. break;
  266. } else if (
  267. this->popTicket_.load(std::memory_order_relaxed) + cap > ticket) {
  268. // May block, but a pop is in progress. No need to expand.
  269. // Get seqlock read section info again in case an expansion
  270. // occurred with an equal or higher ticket.
  271. continue;
  272. } else {
  273. // May block. See if we can expand.
  274. if (tryExpand(state, cap)) {
  275. // This or another thread started an expansion. Get updated info.
  276. continue;
  277. } else {
  278. // Can't expand.
  279. break;
  280. }
  281. }
  282. } while (true);
  283. this->enqueueWithTicketBase(
  284. ticket - offset, slots, cap, stride, std::forward<Args>(args)...);
  285. }
  286. void blockingReadWithTicket(uint64_t& ticket, T& elem) noexcept {
  287. ticket = this->popTicket_++;
  288. Slot* slots;
  289. size_t cap;
  290. int stride;
  291. uint64_t state;
  292. uint64_t offset;
  293. while (!trySeqlockReadSection(state, slots, cap, stride)) {
  294. asm_volatile_pause();
  295. }
  296. // If there was an expansion after the corresponding push ticket
  297. // was issued, adjust accordingly
  298. maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
  299. this->dequeueWithTicketBase(ticket - offset, slots, cap, stride, elem);
  300. }
  301. private:
  302. enum {
  303. kSeqlockBits = 6,
  304. kDefaultMinDynamicCapacity = 10,
  305. kDefaultExpansionMultiplier = 10,
  306. };
  307. size_t dmult_;
  308. // Info about closed slots arrays for use by lagging operations
  309. ClosedArray* closed_;
  310. void initQueue(const size_t cap, const size_t mult) {
  311. this->stride_ = this->computeStride(cap);
  312. this->slots_ = new Slot[cap + 2 * this->kSlotPadding];
  313. this->dstate_.store(0);
  314. this->dcapacity_.store(cap);
  315. dmult_ = mult;
  316. size_t maxClosed = 0;
  317. for (size_t expanded = cap; expanded < this->capacity_; expanded *= mult) {
  318. ++maxClosed;
  319. }
  320. closed_ = (maxClosed > 0) ? new ClosedArray[maxClosed] : nullptr;
  321. }
  322. bool tryObtainReadyPushTicket(
  323. uint64_t& ticket,
  324. Slot*& slots,
  325. size_t& cap,
  326. int& stride) noexcept {
  327. uint64_t state;
  328. do {
  329. ticket = this->pushTicket_.load(std::memory_order_acquire); // A
  330. if (!trySeqlockReadSection(state, slots, cap, stride)) {
  331. asm_volatile_pause();
  332. continue;
  333. }
  334. // If there was an expansion with offset greater than this ticket,
  335. // adjust accordingly
  336. uint64_t offset;
  337. maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
  338. if (slots[this->idx((ticket - offset), cap, stride)].mayEnqueue(
  339. this->turn(ticket - offset, cap))) {
  340. // A slot is ready.
  341. if (this->pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
  342. // Adjust ticket
  343. ticket -= offset;
  344. return true;
  345. } else {
  346. continue;
  347. }
  348. } else {
  349. if (ticket != this->pushTicket_.load(std::memory_order_relaxed)) { // B
  350. // Try again. Ticket changed.
  351. continue;
  352. }
  353. // Likely to block.
  354. // Try to expand unless the ticket is for a closed array
  355. if (offset == getOffset(state)) {
  356. if (tryExpand(state, cap)) {
  357. // This or another thread started an expansion. Get up-to-date info.
  358. continue;
  359. }
  360. }
  361. return false;
  362. }
  363. } while (true);
  364. }
  365. bool tryObtainPromisedPushTicket(
  366. uint64_t& ticket,
  367. Slot*& slots,
  368. size_t& cap,
  369. int& stride) noexcept {
  370. uint64_t state;
  371. do {
  372. ticket = this->pushTicket_.load(std::memory_order_acquire);
  373. auto numPops = this->popTicket_.load(std::memory_order_acquire);
  374. if (!trySeqlockReadSection(state, slots, cap, stride)) {
  375. asm_volatile_pause();
  376. continue;
  377. }
  378. const auto curCap = cap;
  379. // If there was an expansion with offset greater than this ticket,
  380. // adjust accordingly
  381. uint64_t offset;
  382. maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
  383. int64_t n = ticket - numPops;
  384. if (n >= static_cast<ssize_t>(cap)) {
  385. if ((cap == curCap) && tryExpand(state, cap)) {
  386. // This or another thread started an expansion. Start over.
  387. continue;
  388. }
  389. // Can't expand.
  390. ticket -= offset;
  391. return false;
  392. }
  393. if (this->pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
  394. // Adjust ticket
  395. ticket -= offset;
  396. return true;
  397. }
  398. } while (true);
  399. }
  400. bool tryObtainReadyPopTicket(
  401. uint64_t& ticket,
  402. Slot*& slots,
  403. size_t& cap,
  404. int& stride) noexcept {
  405. uint64_t state;
  406. do {
  407. ticket = this->popTicket_.load(std::memory_order_relaxed);
  408. if (!trySeqlockReadSection(state, slots, cap, stride)) {
  409. asm_volatile_pause();
  410. continue;
  411. }
  412. // If there was an expansion after the corresponding push ticket
  413. // was issued, adjust accordingly
  414. uint64_t offset;
  415. maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
  416. if (slots[this->idx((ticket - offset), cap, stride)].mayDequeue(
  417. this->turn(ticket - offset, cap))) {
  418. if (this->popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
  419. // Adjust ticket
  420. ticket -= offset;
  421. return true;
  422. }
  423. } else {
  424. return false;
  425. }
  426. } while (true);
  427. }
  428. bool tryObtainPromisedPopTicket(
  429. uint64_t& ticket,
  430. Slot*& slots,
  431. size_t& cap,
  432. int& stride) noexcept {
  433. uint64_t state;
  434. do {
  435. ticket = this->popTicket_.load(std::memory_order_acquire);
  436. auto numPushes = this->pushTicket_.load(std::memory_order_acquire);
  437. if (!trySeqlockReadSection(state, slots, cap, stride)) {
  438. asm_volatile_pause();
  439. continue;
  440. }
  441. uint64_t offset;
  442. // If there was an expansion after the corresponding push
  443. // ticket was issued, adjust accordingly
  444. maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
  445. if (ticket >= numPushes) {
  446. ticket -= offset;
  447. return false;
  448. }
  449. if (this->popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
  450. ticket -= offset;
  451. return true;
  452. }
  453. } while (true);
  454. }
  455. /// Enqueues an element with a specific ticket number
  456. template <typename... Args>
  457. void enqueueWithTicket(const uint64_t ticket, Args&&... args) noexcept {
  458. Slot* slots;
  459. size_t cap;
  460. int stride;
  461. uint64_t state;
  462. uint64_t offset;
  463. while (!trySeqlockReadSection(state, slots, cap, stride)) {
  464. }
  465. // If there was an expansion after this ticket was issued, adjust
  466. // accordingly
  467. maybeUpdateFromClosed(state, ticket, offset, slots, cap, stride);
  468. this->enqueueWithTicketBase(
  469. ticket - offset, slots, cap, stride, std::forward<Args>(args)...);
  470. }
  471. uint64_t getOffset(const uint64_t state) const noexcept {
  472. return state >> kSeqlockBits;
  473. }
  474. int getNumClosed(const uint64_t state) const noexcept {
  475. return (state & ((1 << kSeqlockBits) - 1)) >> 1;
  476. }
  477. /// Try to expand the queue. Returns true if this expansion was
  478. /// successful or a concurent expansion is in progress. Returns
  479. /// false if the queue has reached its maximum capacity or
  480. /// allocation has failed.
  481. bool tryExpand(const uint64_t state, const size_t cap) noexcept {
  482. if (cap == this->capacity_) {
  483. return false;
  484. }
  485. // Acquire seqlock
  486. uint64_t oldval = state;
  487. assert((state & 1) == 0);
  488. if (this->dstate_.compare_exchange_strong(oldval, state + 1)) {
  489. assert(cap == this->dcapacity_.load());
  490. uint64_t ticket =
  491. 1 + std::max(this->pushTicket_.load(), this->popTicket_.load());
  492. size_t newCapacity = std::min(dmult_ * cap, this->capacity_);
  493. Slot* newSlots =
  494. new (std::nothrow) Slot[newCapacity + 2 * this->kSlotPadding];
  495. if (newSlots == nullptr) {
  496. // Expansion failed. Restore the seqlock
  497. this->dstate_.store(state);
  498. return false;
  499. }
  500. // Successful expansion
  501. // calculate the current ticket offset
  502. uint64_t offset = getOffset(state);
  503. // calculate index in closed array
  504. int index = getNumClosed(state);
  505. assert((index << 1) < (1 << kSeqlockBits));
  506. // fill the info for the closed slots array
  507. closed_[index].offset_ = offset;
  508. closed_[index].slots_ = this->dslots_.load();
  509. closed_[index].capacity_ = cap;
  510. closed_[index].stride_ = this->dstride_.load();
  511. // update the new slots array info
  512. this->dslots_.store(newSlots);
  513. this->dcapacity_.store(newCapacity);
  514. this->dstride_.store(this->computeStride(newCapacity));
  515. // Release the seqlock and record the new ticket offset
  516. this->dstate_.store((ticket << kSeqlockBits) + (2 * (index + 1)));
  517. return true;
  518. } else { // failed to acquire seqlock
  519. // Someone acaquired the seqlock. Go back to the caller and get
  520. // up-to-date info.
  521. return true;
  522. }
  523. }
  524. /// Seqlock read-only section
  525. bool trySeqlockReadSection(
  526. uint64_t& state,
  527. Slot*& slots,
  528. size_t& cap,
  529. int& stride) noexcept {
  530. state = this->dstate_.load(std::memory_order_acquire);
  531. if (state & 1) {
  532. // Locked.
  533. return false;
  534. }
  535. // Start read-only section.
  536. slots = this->dslots_.load(std::memory_order_relaxed);
  537. cap = this->dcapacity_.load(std::memory_order_relaxed);
  538. stride = this->dstride_.load(std::memory_order_relaxed);
  539. // End of read-only section. Validate seqlock.
  540. std::atomic_thread_fence(std::memory_order_acquire);
  541. return (state == this->dstate_.load(std::memory_order_relaxed));
  542. }
  543. /// If there was an expansion after ticket was issued, update local variables
  544. /// of the lagging operation using the most recent closed array with
  545. /// offset <= ticket and return true. Otherwise, return false;
  546. bool maybeUpdateFromClosed(
  547. const uint64_t state,
  548. const uint64_t ticket,
  549. uint64_t& offset,
  550. Slot*& slots,
  551. size_t& cap,
  552. int& stride) noexcept {
  553. offset = getOffset(state);
  554. if (ticket >= offset) {
  555. return false;
  556. }
  557. for (int i = getNumClosed(state) - 1; i >= 0; --i) {
  558. offset = closed_[i].offset_;
  559. if (offset <= ticket) {
  560. slots = closed_[i].slots_;
  561. cap = closed_[i].capacity_;
  562. stride = closed_[i].stride_;
  563. return true;
  564. }
  565. }
  566. // A closed array with offset <= ticket should have been found
  567. assert(false);
  568. return false;
  569. }
  570. };
  571. namespace detail {
  572. /// CRTP specialization of MPMCQueueBase
  573. template <
  574. template <typename T, template <typename> class Atom, bool Dynamic>
  575. class Derived,
  576. typename T,
  577. template <typename> class Atom,
  578. bool Dynamic>
  579. class MPMCQueueBase<Derived<T, Atom, Dynamic>> : boost::noncopyable {
  580. // Note: Using CRTP static casts in several functions of this base
  581. // template instead of making called functions virtual or duplicating
  582. // the code of calling functions in the derived partially specialized
  583. // template
  584. static_assert(
  585. std::is_nothrow_constructible<T, T&&>::value ||
  586. folly::IsRelocatable<T>::value,
  587. "T must be relocatable or have a noexcept move constructor");
  588. public:
  589. typedef T value_type;
  590. using Slot = detail::SingleElementQueue<T, Atom>;
  591. explicit MPMCQueueBase(size_t queueCapacity)
  592. : capacity_(queueCapacity),
  593. pushTicket_(0),
  594. popTicket_(0),
  595. pushSpinCutoff_(0),
  596. popSpinCutoff_(0) {
  597. if (queueCapacity == 0) {
  598. throw std::invalid_argument(
  599. "MPMCQueue with explicit capacity 0 is impossible"
  600. // Stride computation in derived classes would sigfpe if capacity is 0
  601. );
  602. }
  603. // ideally this would be a static assert, but g++ doesn't allow it
  604. assert(
  605. alignof(MPMCQueue<T, Atom>) >= hardware_destructive_interference_size);
  606. assert(
  607. static_cast<uint8_t*>(static_cast<void*>(&popTicket_)) -
  608. static_cast<uint8_t*>(static_cast<void*>(&pushTicket_)) >=
  609. static_cast<ptrdiff_t>(hardware_destructive_interference_size));
  610. }
  611. /// A default-constructed queue is useful because a usable (non-zero
  612. /// capacity) queue can be moved onto it or swapped with it
  613. MPMCQueueBase() noexcept
  614. : capacity_(0),
  615. slots_(nullptr),
  616. stride_(0),
  617. dstate_(0),
  618. dcapacity_(0),
  619. pushTicket_(0),
  620. popTicket_(0),
  621. pushSpinCutoff_(0),
  622. popSpinCutoff_(0) {}
  623. /// IMPORTANT: The move constructor is here to make it easier to perform
  624. /// the initialization phase, it is not safe to use when there are any
  625. /// concurrent accesses (this is not checked).
  626. MPMCQueueBase(MPMCQueueBase<Derived<T, Atom, Dynamic>>&& rhs) noexcept
  627. : capacity_(rhs.capacity_),
  628. slots_(rhs.slots_),
  629. stride_(rhs.stride_),
  630. dstate_(rhs.dstate_.load(std::memory_order_relaxed)),
  631. dcapacity_(rhs.dcapacity_.load(std::memory_order_relaxed)),
  632. pushTicket_(rhs.pushTicket_.load(std::memory_order_relaxed)),
  633. popTicket_(rhs.popTicket_.load(std::memory_order_relaxed)),
  634. pushSpinCutoff_(rhs.pushSpinCutoff_.load(std::memory_order_relaxed)),
  635. popSpinCutoff_(rhs.popSpinCutoff_.load(std::memory_order_relaxed)) {
  636. // relaxed ops are okay for the previous reads, since rhs queue can't
  637. // be in concurrent use
  638. // zero out rhs
  639. rhs.capacity_ = 0;
  640. rhs.slots_ = nullptr;
  641. rhs.stride_ = 0;
  642. rhs.dstate_.store(0, std::memory_order_relaxed);
  643. rhs.dcapacity_.store(0, std::memory_order_relaxed);
  644. rhs.pushTicket_.store(0, std::memory_order_relaxed);
  645. rhs.popTicket_.store(0, std::memory_order_relaxed);
  646. rhs.pushSpinCutoff_.store(0, std::memory_order_relaxed);
  647. rhs.popSpinCutoff_.store(0, std::memory_order_relaxed);
  648. }
  649. /// IMPORTANT: The move operator is here to make it easier to perform
  650. /// the initialization phase, it is not safe to use when there are any
  651. /// concurrent accesses (this is not checked).
  652. MPMCQueueBase<Derived<T, Atom, Dynamic>> const& operator=(
  653. MPMCQueueBase<Derived<T, Atom, Dynamic>>&& rhs) {
  654. if (this != &rhs) {
  655. this->~MPMCQueueBase();
  656. new (this) MPMCQueueBase(std::move(rhs));
  657. }
  658. return *this;
  659. }
  660. /// MPMCQueue can only be safely destroyed when there are no
  661. /// pending enqueuers or dequeuers (this is not checked).
  662. ~MPMCQueueBase() {
  663. delete[] slots_;
  664. }
  665. /// Returns the number of writes (including threads that are blocked waiting
  666. /// to write) minus the number of reads (including threads that are blocked
  667. /// waiting to read). So effectively, it becomes:
  668. /// elements in queue + pending(calls to write) - pending(calls to read).
  669. /// If nothing is pending, then the method returns the actual number of
  670. /// elements in the queue.
  671. /// The returned value can be negative if there are no writers and the queue
  672. /// is empty, but there is one reader that is blocked waiting to read (in
  673. /// which case, the returned size will be -1).
  674. ssize_t size() const noexcept {
  675. // since both pushes and pops increase monotonically, we can get a
  676. // consistent snapshot either by bracketing a read of popTicket_ with
  677. // two reads of pushTicket_ that return the same value, or the other
  678. // way around. We maximize our chances by alternately attempting
  679. // both bracketings.
  680. uint64_t pushes = pushTicket_.load(std::memory_order_acquire); // A
  681. uint64_t pops = popTicket_.load(std::memory_order_acquire); // B
  682. while (true) {
  683. uint64_t nextPushes = pushTicket_.load(std::memory_order_acquire); // C
  684. if (pushes == nextPushes) {
  685. // pushTicket_ didn't change from A (or the previous C) to C,
  686. // so we can linearize at B (or D)
  687. return ssize_t(pushes - pops);
  688. }
  689. pushes = nextPushes;
  690. uint64_t nextPops = popTicket_.load(std::memory_order_acquire); // D
  691. if (pops == nextPops) {
  692. // popTicket_ didn't chance from B (or the previous D), so we
  693. // can linearize at C
  694. return ssize_t(pushes - pops);
  695. }
  696. pops = nextPops;
  697. }
  698. }
  699. /// Returns true if there are no items available for dequeue
  700. bool isEmpty() const noexcept {
  701. return size() <= 0;
  702. }
  703. /// Returns true if there is currently no empty space to enqueue
  704. bool isFull() const noexcept {
  705. // careful with signed -> unsigned promotion, since size can be negative
  706. return size() >= static_cast<ssize_t>(capacity_);
  707. }
  708. /// Returns is a guess at size() for contexts that don't need a precise
  709. /// value, such as stats. More specifically, it returns the number of writes
  710. /// minus the number of reads, but after reading the number of writes, more
  711. /// writers could have came before the number of reads was sampled,
  712. /// and this method doesn't protect against such case.
  713. /// The returned value can be negative.
  714. ssize_t sizeGuess() const noexcept {
  715. return writeCount() - readCount();
  716. }
  717. /// Doesn't change
  718. size_t capacity() const noexcept {
  719. return capacity_;
  720. }
  721. /// Doesn't change for non-dynamic
  722. size_t allocatedCapacity() const noexcept {
  723. return capacity_;
  724. }
  725. /// Returns the total number of calls to blockingWrite or successful
  726. /// calls to write, including those blockingWrite calls that are
  727. /// currently blocking
  728. uint64_t writeCount() const noexcept {
  729. return pushTicket_.load(std::memory_order_acquire);
  730. }
  731. /// Returns the total number of calls to blockingRead or successful
  732. /// calls to read, including those blockingRead calls that are currently
  733. /// blocking
  734. uint64_t readCount() const noexcept {
  735. return popTicket_.load(std::memory_order_acquire);
  736. }
  737. /// Enqueues a T constructed from args, blocking until space is
  738. /// available. Note that this method signature allows enqueue via
  739. /// move, if args is a T rvalue, via copy, if args is a T lvalue, or
  740. /// via emplacement if args is an initializer list that can be passed
  741. /// to a T constructor.
  742. template <typename... Args>
  743. void blockingWrite(Args&&... args) noexcept {
  744. enqueueWithTicketBase(
  745. pushTicket_++, slots_, capacity_, stride_, std::forward<Args>(args)...);
  746. }
  747. /// If an item can be enqueued with no blocking, does so and returns
  748. /// true, otherwise returns false. This method is similar to
  749. /// writeIfNotFull, but if you don't have a specific need for that
  750. /// method you should use this one.
  751. ///
  752. /// One of the common usages of this method is to enqueue via the
  753. /// move constructor, something like q.write(std::move(x)). If write
  754. /// returns false because the queue is full then x has not actually been
  755. /// consumed, which looks strange. To understand why it is actually okay
  756. /// to use x afterward, remember that std::move is just a typecast that
  757. /// provides an rvalue reference that enables use of a move constructor
  758. /// or operator. std::move doesn't actually move anything. It could
  759. /// more accurately be called std::rvalue_cast or std::move_permission.
  760. template <typename... Args>
  761. bool write(Args&&... args) noexcept {
  762. uint64_t ticket;
  763. Slot* slots;
  764. size_t cap;
  765. int stride;
  766. if (static_cast<Derived<T, Atom, Dynamic>*>(this)->tryObtainReadyPushTicket(
  767. ticket, slots, cap, stride)) {
  768. // we have pre-validated that the ticket won't block
  769. enqueueWithTicketBase(
  770. ticket, slots, cap, stride, std::forward<Args>(args)...);
  771. return true;
  772. } else {
  773. return false;
  774. }
  775. }
  776. template <class Clock, typename... Args>
  777. bool tryWriteUntil(
  778. const std::chrono::time_point<Clock>& when,
  779. Args&&... args) noexcept {
  780. uint64_t ticket;
  781. Slot* slots;
  782. size_t cap;
  783. int stride;
  784. if (tryObtainPromisedPushTicketUntil(ticket, slots, cap, stride, when)) {
  785. // we have pre-validated that the ticket won't block, or rather that
  786. // it won't block longer than it takes another thread to dequeue an
  787. // element from the slot it identifies.
  788. enqueueWithTicketBase(
  789. ticket, slots, cap, stride, std::forward<Args>(args)...);
  790. return true;
  791. } else {
  792. return false;
  793. }
  794. }
  795. /// If the queue is not full, enqueues and returns true, otherwise
  796. /// returns false. Unlike write this method can be blocked by another
  797. /// thread, specifically a read that has linearized (been assigned
  798. /// a ticket) but not yet completed. If you don't really need this
  799. /// function you should probably use write.
  800. ///
  801. /// MPMCQueue isn't lock-free, so just because a read operation has
  802. /// linearized (and isFull is false) doesn't mean that space has been
  803. /// made available for another write. In this situation write will
  804. /// return false, but writeIfNotFull will wait for the dequeue to finish.
  805. /// This method is required if you are composing queues and managing
  806. /// your own wakeup, because it guarantees that after every successful
  807. /// write a readIfNotEmpty will succeed.
  808. template <typename... Args>
  809. bool writeIfNotFull(Args&&... args) noexcept {
  810. uint64_t ticket;
  811. Slot* slots;
  812. size_t cap;
  813. int stride;
  814. if (static_cast<Derived<T, Atom, Dynamic>*>(this)
  815. ->tryObtainPromisedPushTicket(ticket, slots, cap, stride)) {
  816. // some other thread is already dequeuing the slot into which we
  817. // are going to enqueue, but we might have to wait for them to finish
  818. enqueueWithTicketBase(
  819. ticket, slots, cap, stride, std::forward<Args>(args)...);
  820. return true;
  821. } else {
  822. return false;
  823. }
  824. }
  825. /// Moves a dequeued element onto elem, blocking until an element
  826. /// is available
  827. void blockingRead(T& elem) noexcept {
  828. uint64_t ticket;
  829. static_cast<Derived<T, Atom, Dynamic>*>(this)->blockingReadWithTicket(
  830. ticket, elem);
  831. }
  832. /// Same as blockingRead() but also records the ticket nunmer
  833. void blockingReadWithTicket(uint64_t& ticket, T& elem) noexcept {
  834. assert(capacity_ != 0);
  835. ticket = popTicket_++;
  836. dequeueWithTicketBase(ticket, slots_, capacity_, stride_, elem);
  837. }
  838. /// If an item can be dequeued with no blocking, does so and returns
  839. /// true, otherwise returns false.
  840. bool read(T& elem) noexcept {
  841. uint64_t ticket;
  842. return readAndGetTicket(ticket, elem);
  843. }
  844. /// Same as read() but also records the ticket nunmer
  845. bool readAndGetTicket(uint64_t& ticket, T& elem) noexcept {
  846. Slot* slots;
  847. size_t cap;
  848. int stride;
  849. if (static_cast<Derived<T, Atom, Dynamic>*>(this)->tryObtainReadyPopTicket(
  850. ticket, slots, cap, stride)) {
  851. // the ticket has been pre-validated to not block
  852. dequeueWithTicketBase(ticket, slots, cap, stride, elem);
  853. return true;
  854. } else {
  855. return false;
  856. }
  857. }
  858. template <class Clock, typename... Args>
  859. bool tryReadUntil(
  860. const std::chrono::time_point<Clock>& when,
  861. T& elem) noexcept {
  862. uint64_t ticket;
  863. Slot* slots;
  864. size_t cap;
  865. int stride;
  866. if (tryObtainPromisedPopTicketUntil(ticket, slots, cap, stride, when)) {
  867. // we have pre-validated that the ticket won't block, or rather that
  868. // it won't block longer than it takes another thread to enqueue an
  869. // element on the slot it identifies.
  870. dequeueWithTicketBase(ticket, slots, cap, stride, elem);
  871. return true;
  872. } else {
  873. return false;
  874. }
  875. }
  876. /// If the queue is not empty, dequeues and returns true, otherwise
  877. /// returns false. If the matching write is still in progress then this
  878. /// method may block waiting for it. If you don't rely on being able
  879. /// to dequeue (such as by counting completed write) then you should
  880. /// prefer read.
  881. bool readIfNotEmpty(T& elem) noexcept {
  882. uint64_t ticket;
  883. Slot* slots;
  884. size_t cap;
  885. int stride;
  886. if (static_cast<Derived<T, Atom, Dynamic>*>(this)
  887. ->tryObtainPromisedPopTicket(ticket, slots, cap, stride)) {
  888. // the matching enqueue already has a ticket, but might not be done
  889. dequeueWithTicketBase(ticket, slots, cap, stride, elem);
  890. return true;
  891. } else {
  892. return false;
  893. }
  894. }
  895. protected:
  896. enum {
  897. /// Once every kAdaptationFreq we will spin longer, to try to estimate
  898. /// the proper spin backoff
  899. kAdaptationFreq = 128,
  900. /// To avoid false sharing in slots_ with neighboring memory
  901. /// allocations, we pad it with this many SingleElementQueue-s at
  902. /// each end
  903. kSlotPadding =
  904. (hardware_destructive_interference_size - 1) / sizeof(Slot) + 1
  905. };
  906. /// The maximum number of items in the queue at once
  907. alignas(hardware_destructive_interference_size) size_t capacity_;
  908. /// Anonymous union for use when Dynamic = false and true, respectively
  909. union {
  910. /// An array of capacity_ SingleElementQueue-s, each of which holds
  911. /// either 0 or 1 item. We over-allocate by 2 * kSlotPadding and don't
  912. /// touch the slots at either end, to avoid false sharing
  913. Slot* slots_;
  914. /// Current dynamic slots array of dcapacity_ SingleElementQueue-s
  915. Atom<Slot*> dslots_;
  916. };
  917. /// Anonymous union for use when Dynamic = false and true, respectively
  918. union {
  919. /// The number of slots_ indices that we advance for each ticket, to
  920. /// avoid false sharing. Ideally slots_[i] and slots_[i + stride_]
  921. /// aren't on the same cache line
  922. int stride_;
  923. /// Current stride
  924. Atom<int> dstride_;
  925. };
  926. /// The following two memebers are used by dynamic MPMCQueue.
  927. /// Ideally they should be in MPMCQueue<T,Atom,true>, but we get
  928. /// better cache locality if they are in the same cache line as
  929. /// dslots_ and dstride_.
  930. ///
  931. /// Dynamic state. A packed seqlock and ticket offset
  932. Atom<uint64_t> dstate_;
  933. /// Dynamic capacity
  934. Atom<size_t> dcapacity_;
  935. /// Enqueuers get tickets from here
  936. alignas(hardware_destructive_interference_size) Atom<uint64_t> pushTicket_;
  937. /// Dequeuers get tickets from here
  938. alignas(hardware_destructive_interference_size) Atom<uint64_t> popTicket_;
  939. /// This is how many times we will spin before using FUTEX_WAIT when
  940. /// the queue is full on enqueue, adaptively computed by occasionally
  941. /// spinning for longer and smoothing with an exponential moving average
  942. alignas(
  943. hardware_destructive_interference_size) Atom<uint32_t> pushSpinCutoff_;
  944. /// The adaptive spin cutoff when the queue is empty on dequeue
  945. alignas(hardware_destructive_interference_size) Atom<uint32_t> popSpinCutoff_;
  946. /// Alignment doesn't prevent false sharing at the end of the struct,
  947. /// so fill out the last cache line
  948. char pad_[hardware_destructive_interference_size - sizeof(Atom<uint32_t>)];
  949. /// We assign tickets in increasing order, but we don't want to
  950. /// access neighboring elements of slots_ because that will lead to
  951. /// false sharing (multiple cores accessing the same cache line even
  952. /// though they aren't accessing the same bytes in that cache line).
  953. /// To avoid this we advance by stride slots per ticket.
  954. ///
  955. /// We need gcd(capacity, stride) to be 1 so that we will use all
  956. /// of the slots. We ensure this by only considering prime strides,
  957. /// which either have no common divisors with capacity or else have
  958. /// a zero remainder after dividing by capacity. That is sufficient
  959. /// to guarantee correctness, but we also want to actually spread the
  960. /// accesses away from each other to avoid false sharing (consider a
  961. /// stride of 7 with a capacity of 8). To that end we try a few taking
  962. /// care to observe that advancing by -1 is as bad as advancing by 1
  963. /// when in comes to false sharing.
  964. ///
  965. /// The simple way to avoid false sharing would be to pad each
  966. /// SingleElementQueue, but since we have capacity_ of them that could
  967. /// waste a lot of space.
  968. static int computeStride(size_t capacity) noexcept {
  969. static const int smallPrimes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23};
  970. int bestStride = 1;
  971. size_t bestSep = 1;
  972. for (int stride : smallPrimes) {
  973. if ((stride % capacity) == 0 || (capacity % stride) == 0) {
  974. continue;
  975. }
  976. size_t sep = stride % capacity;
  977. sep = std::min(sep, capacity - sep);
  978. if (sep > bestSep) {
  979. bestStride = stride;
  980. bestSep = sep;
  981. }
  982. }
  983. return bestStride;
  984. }
  985. /// Returns the index into slots_ that should be used when enqueuing or
  986. /// dequeuing with the specified ticket
  987. size_t idx(uint64_t ticket, size_t cap, int stride) noexcept {
  988. return ((ticket * stride) % cap) + kSlotPadding;
  989. }
  990. /// Maps an enqueue or dequeue ticket to the turn should be used at the
  991. /// corresponding SingleElementQueue
  992. uint32_t turn(uint64_t ticket, size_t cap) noexcept {
  993. assert(cap != 0);
  994. return uint32_t(ticket / cap);
  995. }
  996. /// Tries to obtain a push ticket for which SingleElementQueue::enqueue
  997. /// won't block. Returns true on immediate success, false on immediate
  998. /// failure.
  999. bool tryObtainReadyPushTicket(
  1000. uint64_t& ticket,
  1001. Slot*& slots,
  1002. size_t& cap,
  1003. int& stride) noexcept {
  1004. ticket = pushTicket_.load(std::memory_order_acquire); // A
  1005. slots = slots_;
  1006. cap = capacity_;
  1007. stride = stride_;
  1008. while (true) {
  1009. if (!slots[idx(ticket, cap, stride)].mayEnqueue(turn(ticket, cap))) {
  1010. // if we call enqueue(ticket, ...) on the SingleElementQueue
  1011. // right now it would block, but this might no longer be the next
  1012. // ticket. We can increase the chance of tryEnqueue success under
  1013. // contention (without blocking) by rechecking the ticket dispenser
  1014. auto prev = ticket;
  1015. ticket = pushTicket_.load(std::memory_order_acquire); // B
  1016. if (prev == ticket) {
  1017. // mayEnqueue was bracketed by two reads (A or prev B or prev
  1018. // failing CAS to B), so we are definitely unable to enqueue
  1019. return false;
  1020. }
  1021. } else {
  1022. // we will bracket the mayEnqueue check with a read (A or prev B
  1023. // or prev failing CAS) and the following CAS. If the CAS fails
  1024. // it will effect a load of pushTicket_
  1025. if (pushTicket_.compare_exchange_strong(ticket, ticket + 1)) {
  1026. return true;
  1027. }
  1028. }
  1029. }
  1030. }
  1031. /// Tries until when to obtain a push ticket for which
  1032. /// SingleElementQueue::enqueue won't block. Returns true on success, false
  1033. /// on failure.
  1034. /// ticket is filled on success AND failure.
  1035. template <class Clock>
  1036. bool tryObtainPromisedPushTicketUntil(
  1037. uint64_t& ticket,
  1038. Slot*& slots,
  1039. size_t& cap,
  1040. int& stride,
  1041. const std::chrono::time_point<Clock>& when) noexcept {
  1042. bool deadlineReached = false;
  1043. while (!deadlineReached) {
  1044. if (static_cast<Derived<T, Atom, Dynamic>*>(this)
  1045. ->tryObtainPromisedPushTicket(ticket, slots, cap, stride)) {
  1046. return true;
  1047. }
  1048. // ticket is a blocking ticket until the preceding ticket has been
  1049. // processed: wait until this ticket's turn arrives. We have not reserved
  1050. // this ticket so we will have to re-attempt to get a non-blocking ticket
  1051. // if we wake up before we time-out.
  1052. deadlineReached =
  1053. !slots[idx(ticket, cap, stride)].tryWaitForEnqueueTurnUntil(
  1054. turn(ticket, cap),
  1055. pushSpinCutoff_,
  1056. (ticket % kAdaptationFreq) == 0,
  1057. when);
  1058. }
  1059. return false;
  1060. }
  1061. /// Tries to obtain a push ticket which can be satisfied if all
  1062. /// in-progress pops complete. This function does not block, but
  1063. /// blocking may be required when using the returned ticket if some
  1064. /// other thread's pop is still in progress (ticket has been granted but
  1065. /// pop has not yet completed).
  1066. bool tryObtainPromisedPushTicket(
  1067. uint64_t& ticket,
  1068. Slot*& slots,
  1069. size_t& cap,
  1070. int& stride) noexcept {
  1071. auto numPushes = pushTicket_.load(std::memory_order_acquire); // A
  1072. slots = slots_;
  1073. cap = capacity_;
  1074. stride = stride_;
  1075. while (true) {
  1076. ticket = numPushes;
  1077. const auto numPops = popTicket_.load(std::memory_order_acquire); // B
  1078. // n will be negative if pops are pending
  1079. const int64_t n = int64_t(numPushes - numPops);
  1080. if (n >= static_cast<ssize_t>(capacity_)) {
  1081. // Full, linearize at B. We don't need to recheck the read we
  1082. // performed at A, because if numPushes was stale at B then the
  1083. // real numPushes value is even worse
  1084. return false;
  1085. }
  1086. if (pushTicket_.compare_exchange_strong(numPushes, numPushes + 1)) {
  1087. return true;
  1088. }
  1089. }
  1090. }
  1091. /// Tries to obtain a pop ticket for which SingleElementQueue::dequeue
  1092. /// won't block. Returns true on immediate success, false on immediate
  1093. /// failure.
  1094. bool tryObtainReadyPopTicket(
  1095. uint64_t& ticket,
  1096. Slot*& slots,
  1097. size_t& cap,
  1098. int& stride) noexcept {
  1099. ticket = popTicket_.load(std::memory_order_acquire);
  1100. slots = slots_;
  1101. cap = capacity_;
  1102. stride = stride_;
  1103. while (true) {
  1104. if (!slots[idx(ticket, cap, stride)].mayDequeue(turn(ticket, cap))) {
  1105. auto prev = ticket;
  1106. ticket = popTicket_.load(std::memory_order_acquire);
  1107. if (prev == ticket) {
  1108. return false;
  1109. }
  1110. } else {
  1111. if (popTicket_.compare_exchange_strong(ticket, ticket + 1)) {
  1112. return true;
  1113. }
  1114. }
  1115. }
  1116. }
  1117. /// Tries until when to obtain a pop ticket for which
  1118. /// SingleElementQueue::dequeue won't block. Returns true on success, false
  1119. /// on failure.
  1120. /// ticket is filled on success AND failure.
  1121. template <class Clock>
  1122. bool tryObtainPromisedPopTicketUntil(
  1123. uint64_t& ticket,
  1124. Slot*& slots,
  1125. size_t& cap,
  1126. int& stride,
  1127. const std::chrono::time_point<Clock>& when) noexcept {
  1128. bool deadlineReached = false;
  1129. while (!deadlineReached) {
  1130. if (static_cast<Derived<T, Atom, Dynamic>*>(this)
  1131. ->tryObtainPromisedPopTicket(ticket, slots, cap, stride)) {
  1132. return true;
  1133. }
  1134. // ticket is a blocking ticket until the preceding ticket has been
  1135. // processed: wait until this ticket's turn arrives. We have not reserved
  1136. // this ticket so we will have to re-attempt to get a non-blocking ticket
  1137. // if we wake up before we time-out.
  1138. deadlineReached =
  1139. !slots[idx(ticket, cap, stride)].tryWaitForDequeueTurnUntil(
  1140. turn(ticket, cap),
  1141. pushSpinCutoff_,
  1142. (ticket % kAdaptationFreq) == 0,
  1143. when);
  1144. }
  1145. return false;
  1146. }
  1147. /// Similar to tryObtainReadyPopTicket, but returns a pop ticket whose
  1148. /// corresponding push ticket has already been handed out, rather than
  1149. /// returning one whose corresponding push ticket has already been
  1150. /// completed. This means that there is a possibility that the caller
  1151. /// will block when using the ticket, but it allows the user to rely on
  1152. /// the fact that if enqueue has succeeded, tryObtainPromisedPopTicket
  1153. /// will return true. The "try" part of this is that we won't have
  1154. /// to block waiting for someone to call enqueue, although we might
  1155. /// have to block waiting for them to finish executing code inside the
  1156. /// MPMCQueue itself.
  1157. bool tryObtainPromisedPopTicket(
  1158. uint64_t& ticket,
  1159. Slot*& slots,
  1160. size_t& cap,
  1161. int& stride) noexcept {
  1162. auto numPops = popTicket_.load(std::memory_order_acquire); // A
  1163. slots = slots_;
  1164. cap = capacity_;
  1165. stride = stride_;
  1166. while (true) {
  1167. ticket = numPops;
  1168. const auto numPushes = pushTicket_.load(std::memory_order_acquire); // B
  1169. if (numPops >= numPushes) {
  1170. // Empty, or empty with pending pops. Linearize at B. We don't
  1171. // need to recheck the read we performed at A, because if numPops
  1172. // is stale then the fresh value is larger and the >= is still true
  1173. return false;
  1174. }
  1175. if (popTicket_.compare_exchange_strong(numPops, numPops + 1)) {
  1176. return true;
  1177. }
  1178. }
  1179. }
  1180. // Given a ticket, constructs an enqueued item using args
  1181. template <typename... Args>
  1182. void enqueueWithTicketBase(
  1183. uint64_t ticket,
  1184. Slot* slots,
  1185. size_t cap,
  1186. int stride,
  1187. Args&&... args) noexcept {
  1188. slots[idx(ticket, cap, stride)].enqueue(
  1189. turn(ticket, cap),
  1190. pushSpinCutoff_,
  1191. (ticket % kAdaptationFreq) == 0,
  1192. std::forward<Args>(args)...);
  1193. }
  1194. // To support tracking ticket numbers in MPMCPipelineStageImpl
  1195. template <typename... Args>
  1196. void enqueueWithTicket(uint64_t ticket, Args&&... args) noexcept {
  1197. enqueueWithTicketBase(
  1198. ticket, slots_, capacity_, stride_, std::forward<Args>(args)...);
  1199. }
  1200. // Given a ticket, dequeues the corresponding element
  1201. void dequeueWithTicketBase(
  1202. uint64_t ticket,
  1203. Slot* slots,
  1204. size_t cap,
  1205. int stride,
  1206. T& elem) noexcept {
  1207. assert(cap != 0);
  1208. slots[idx(ticket, cap, stride)].dequeue(
  1209. turn(ticket, cap),
  1210. popSpinCutoff_,
  1211. (ticket % kAdaptationFreq) == 0,
  1212. elem);
  1213. }
  1214. };
  1215. /// SingleElementQueue implements a blocking queue that holds at most one
  1216. /// item, and that requires its users to assign incrementing identifiers
  1217. /// (turns) to each enqueue and dequeue operation. Note that the turns
  1218. /// used by SingleElementQueue are doubled inside the TurnSequencer
  1219. template <typename T, template <typename> class Atom>
  1220. struct SingleElementQueue {
  1221. ~SingleElementQueue() noexcept {
  1222. if ((sequencer_.uncompletedTurnLSB() & 1) == 1) {
  1223. // we are pending a dequeue, so we have a constructed item
  1224. destroyContents();
  1225. }
  1226. }
  1227. /// enqueue using in-place noexcept construction
  1228. template <
  1229. typename... Args,
  1230. typename = typename std::enable_if<
  1231. std::is_nothrow_constructible<T, Args...>::value>::type>
  1232. void enqueue(
  1233. const uint32_t turn,
  1234. Atom<uint32_t>& spinCutoff,
  1235. const bool updateSpinCutoff,
  1236. Args&&... args) noexcept {
  1237. sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
  1238. new (&contents_) T(std::forward<Args>(args)...);
  1239. sequencer_.completeTurn(turn * 2);
  1240. }
  1241. /// enqueue using move construction, either real (if
  1242. /// is_nothrow_move_constructible) or simulated using relocation and
  1243. /// default construction (if IsRelocatable and is_nothrow_constructible)
  1244. template <
  1245. typename = typename std::enable_if<
  1246. (folly::IsRelocatable<T>::value &&
  1247. std::is_nothrow_constructible<T>::value) ||
  1248. std::is_nothrow_constructible<T, T&&>::value>::type>
  1249. void enqueue(
  1250. const uint32_t turn,
  1251. Atom<uint32_t>& spinCutoff,
  1252. const bool updateSpinCutoff,
  1253. T&& goner) noexcept {
  1254. enqueueImpl(
  1255. turn,
  1256. spinCutoff,
  1257. updateSpinCutoff,
  1258. std::move(goner),
  1259. typename std::conditional<
  1260. std::is_nothrow_constructible<T, T&&>::value,
  1261. ImplByMove,
  1262. ImplByRelocation>::type());
  1263. }
  1264. /// Waits until either:
  1265. /// 1: the dequeue turn preceding the given enqueue turn has arrived
  1266. /// 2: the given deadline has arrived
  1267. /// Case 1 returns true, case 2 returns false.
  1268. template <class Clock>
  1269. bool tryWaitForEnqueueTurnUntil(
  1270. const uint32_t turn,
  1271. Atom<uint32_t>& spinCutoff,
  1272. const bool updateSpinCutoff,
  1273. const std::chrono::time_point<Clock>& when) noexcept {
  1274. return sequencer_.tryWaitForTurn(
  1275. turn * 2, spinCutoff, updateSpinCutoff, &when) !=
  1276. TurnSequencer<Atom>::TryWaitResult::TIMEDOUT;
  1277. }
  1278. bool mayEnqueue(const uint32_t turn) const noexcept {
  1279. return sequencer_.isTurn(turn * 2);
  1280. }
  1281. void dequeue(
  1282. uint32_t turn,
  1283. Atom<uint32_t>& spinCutoff,
  1284. const bool updateSpinCutoff,
  1285. T& elem) noexcept {
  1286. dequeueImpl(
  1287. turn,
  1288. spinCutoff,
  1289. updateSpinCutoff,
  1290. elem,
  1291. typename std::conditional<
  1292. folly::IsRelocatable<T>::value,
  1293. ImplByRelocation,
  1294. ImplByMove>::type());
  1295. }
  1296. /// Waits until either:
  1297. /// 1: the enqueue turn preceding the given dequeue turn has arrived
  1298. /// 2: the given deadline has arrived
  1299. /// Case 1 returns true, case 2 returns false.
  1300. template <class Clock>
  1301. bool tryWaitForDequeueTurnUntil(
  1302. const uint32_t turn,
  1303. Atom<uint32_t>& spinCutoff,
  1304. const bool updateSpinCutoff,
  1305. const std::chrono::time_point<Clock>& when) noexcept {
  1306. return sequencer_.tryWaitForTurn(
  1307. turn * 2 + 1, spinCutoff, updateSpinCutoff, &when) !=
  1308. TurnSequencer<Atom>::TryWaitResult::TIMEDOUT;
  1309. }
  1310. bool mayDequeue(const uint32_t turn) const noexcept {
  1311. return sequencer_.isTurn(turn * 2 + 1);
  1312. }
  1313. private:
  1314. /// Storage for a T constructed with placement new
  1315. typename std::aligned_storage<sizeof(T), alignof(T)>::type contents_;
  1316. /// Even turns are pushes, odd turns are pops
  1317. TurnSequencer<Atom> sequencer_;
  1318. T* ptr() noexcept {
  1319. return static_cast<T*>(static_cast<void*>(&contents_));
  1320. }
  1321. void destroyContents() noexcept {
  1322. try {
  1323. ptr()->~T();
  1324. } catch (...) {
  1325. // g++ doesn't seem to have std::is_nothrow_destructible yet
  1326. }
  1327. #ifndef NDEBUG
  1328. memset(&contents_, 'Q', sizeof(T));
  1329. #endif
  1330. }
  1331. /// Tag classes for dispatching to enqueue/dequeue implementation.
  1332. struct ImplByRelocation {};
  1333. struct ImplByMove {};
  1334. /// enqueue using nothrow move construction.
  1335. void enqueueImpl(
  1336. const uint32_t turn,
  1337. Atom<uint32_t>& spinCutoff,
  1338. const bool updateSpinCutoff,
  1339. T&& goner,
  1340. ImplByMove) noexcept {
  1341. sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
  1342. new (&contents_) T(std::move(goner));
  1343. sequencer_.completeTurn(turn * 2);
  1344. }
  1345. /// enqueue by simulating nothrow move with relocation, followed by
  1346. /// default construction to a noexcept relocation.
  1347. void enqueueImpl(
  1348. const uint32_t turn,
  1349. Atom<uint32_t>& spinCutoff,
  1350. const bool updateSpinCutoff,
  1351. T&& goner,
  1352. ImplByRelocation) noexcept {
  1353. sequencer_.waitForTurn(turn * 2, spinCutoff, updateSpinCutoff);
  1354. memcpy(&contents_, &goner, sizeof(T));
  1355. sequencer_.completeTurn(turn * 2);
  1356. new (&goner) T();
  1357. }
  1358. /// dequeue by destructing followed by relocation. This version is preferred,
  1359. /// because as much work as possible can be done before waiting.
  1360. void dequeueImpl(
  1361. uint32_t turn,
  1362. Atom<uint32_t>& spinCutoff,
  1363. const bool updateSpinCutoff,
  1364. T& elem,
  1365. ImplByRelocation) noexcept {
  1366. try {
  1367. elem.~T();
  1368. } catch (...) {
  1369. // unlikely, but if we don't complete our turn the queue will die
  1370. }
  1371. sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
  1372. memcpy(&elem, &contents_, sizeof(T));
  1373. sequencer_.completeTurn(turn * 2 + 1);
  1374. }
  1375. /// dequeue by nothrow move assignment.
  1376. void dequeueImpl(
  1377. uint32_t turn,
  1378. Atom<uint32_t>& spinCutoff,
  1379. const bool updateSpinCutoff,
  1380. T& elem,
  1381. ImplByMove) noexcept {
  1382. sequencer_.waitForTurn(turn * 2 + 1, spinCutoff, updateSpinCutoff);
  1383. elem = std::move(*ptr());
  1384. destroyContents();
  1385. sequencer_.completeTurn(turn * 2 + 1);
  1386. }
  1387. };
  1388. } // namespace detail
  1389. } // namespace folly