mpsc_read_as_filled.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. #pragma once
  2. /*
  3. Completely wait-free queue, multiple producers - one consumer. Strict order.
  4. The queue algorithm is using concept of virtual infinite array.
  5. A producer takes a number from a counter and atomically increments the counter.
  6. The number taken is a number of a slot for the producer to put a new message
  7. into infinite array.
  8. Then producer constructs a virtual infinite array by bidirectional linked list
  9. of blocks. Each block contains several slots.
  10. There is a hint pointer which optimistically points to the last block
  11. of the list and never goes backward.
  12. Consumer exploits the property of the hint pointer always going forward
  13. to free old blocks eventually. Consumer periodically read the hint pointer
  14. and the counter and thus deduce producers which potentially holds the pointer
  15. to a block. Consumer can free the block if all that producers filled their
  16. slots and left the queue.
  17. No producer can stop the progress for other producers.
  18. Consumer can't stop the progress for producers.
  19. Consumer can skip not-yet-filled slots and read them later.
  20. Thus no producer can stop the progress for consumer.
  21. The algorithm is virtually strictly ordered because it skips slots only
  22. if it is really does not matter in which order the slots were produced and
  23. consumed.
  24. WARNING: there is no wait&notify mechanic for consumer,
  25. consumer receives nullptr if queue was empty.
  26. WARNING: though the algorithm itself is completely wait-free
  27. but producers and consumer could be blocked by memory allocator
  28. WARNING: copy constructors of the queue are not thread-safe
  29. */
  30. #include <util/generic/deque.h>
  31. #include <util/generic/ptr.h>
  32. #include <library/cpp/deprecated/atomic/atomic.h>
  33. #include <util/system/spinlock.h>
  34. #include "tune.h"
  35. namespace NThreading {
  36. namespace NReadAsFilledPrivate {
  37. typedef void* TMsgLink;
  38. static constexpr ui32 DEFAULT_BUNCH_SIZE = 251;
  39. struct TEmpty {
  40. };
  41. struct TEmptyAux {
  42. TEmptyAux Retrieve() const {
  43. return TEmptyAux();
  44. }
  45. void Store(TEmptyAux&) {
  46. }
  47. static constexpr TEmptyAux Zero() {
  48. return TEmptyAux();
  49. }
  50. };
  51. template <typename TAux>
  52. struct TSlot {
  53. TMsgLink volatile Msg;
  54. TAux AuxiliaryData;
  55. inline void Store(TAux& aux) {
  56. AuxiliaryData.Store(aux);
  57. }
  58. inline TAux Retrieve() const {
  59. return AuxiliaryData.Retrieve();
  60. }
  61. static TSlot<TAux> NullElem() {
  62. return {nullptr, TAux::Zero()};
  63. }
  64. static TSlot<TAux> Pair(TMsgLink msg, TAux aux) {
  65. return {msg, std::move(aux)};
  66. }
  67. };
  68. template <>
  69. struct TSlot<TEmptyAux> {
  70. TMsgLink volatile Msg;
  71. inline void Store(TEmptyAux&) {
  72. }
  73. inline TEmptyAux Retrieve() const {
  74. return TEmptyAux();
  75. }
  76. static TSlot<TEmptyAux> NullElem() {
  77. return {nullptr};
  78. }
  79. static TSlot<TEmptyAux> Pair(TMsgLink msg, TEmptyAux) {
  80. return {msg};
  81. }
  82. };
  83. enum TPushResult {
  84. PUSH_RESULT_OK,
  85. PUSH_RESULT_BACKWARD,
  86. PUSH_RESULT_FORWARD,
  87. };
  88. template <ui32 BUNCH_SIZE = DEFAULT_BUNCH_SIZE,
  89. typename TBase = TEmpty,
  90. typename TAux = TEmptyAux>
  91. struct TMsgBunch: public TBase {
  92. static constexpr size_t RELEASE_SIZE = BUNCH_SIZE * 2;
  93. ui64 FirstSlot;
  94. TSlot<TAux> LinkArray[BUNCH_SIZE];
  95. TMsgBunch* volatile NextBunch;
  96. TMsgBunch* volatile BackLink;
  97. ui64 volatile Token;
  98. TMsgBunch* volatile NextToken;
  99. /* this push can return PUSH_RESULT_BLOCKED */
  100. inline TPushResult Push(TMsgLink msg, ui64 slot, TAux auxiliary) {
  101. if (Y_UNLIKELY(slot < FirstSlot)) {
  102. return PUSH_RESULT_BACKWARD;
  103. }
  104. if (Y_UNLIKELY(slot >= FirstSlot + BUNCH_SIZE)) {
  105. return PUSH_RESULT_FORWARD;
  106. }
  107. LinkArray[slot - FirstSlot].Store(auxiliary);
  108. AtomicSet(LinkArray[slot - FirstSlot].Msg, msg);
  109. return PUSH_RESULT_OK;
  110. }
  111. inline bool IsSlotHere(ui64 slot) {
  112. return slot < FirstSlot + BUNCH_SIZE;
  113. }
  114. inline TMsgLink GetSlot(ui64 slot) const {
  115. return AtomicGet(LinkArray[slot - FirstSlot].Msg);
  116. }
  117. inline TSlot<TAux> GetSlotAux(ui64 slot) const {
  118. auto msg = GetSlot(slot);
  119. auto aux = LinkArray[slot - FirstSlot].Retrieve();
  120. return TSlot<TAux>::Pair(msg, aux);
  121. }
  122. inline TMsgBunch* GetNextBunch() const {
  123. return AtomicGet(NextBunch);
  124. }
  125. inline bool SetNextBunch(TMsgBunch* ptr) {
  126. return AtomicCas(&NextBunch, ptr, nullptr);
  127. }
  128. inline TMsgBunch* GetBackLink() const {
  129. return AtomicGet(BackLink);
  130. }
  131. inline TMsgBunch* GetToken(ui64 slot) {
  132. return reinterpret_cast<TMsgBunch*>(
  133. LinkArray[slot - FirstSlot].Msg);
  134. }
  135. inline void IncrementToken() {
  136. AtomicIncrement(Token);
  137. }
  138. // the object could be destroyed after this method
  139. inline void DecrementToken() {
  140. if (Y_UNLIKELY(AtomicDecrement(Token) == RELEASE_SIZE)) {
  141. Release(this);
  142. AtomicGet(NextToken)->DecrementToken();
  143. // this could be invalid here
  144. }
  145. }
  146. // the object could be destroyed after this method
  147. inline void SetNextToken(TMsgBunch* next) {
  148. AtomicSet(NextToken, next);
  149. if (Y_UNLIKELY(AtomicAdd(Token, RELEASE_SIZE) == RELEASE_SIZE)) {
  150. Release(this);
  151. next->DecrementToken();
  152. }
  153. // this could be invalid here
  154. }
  155. TMsgBunch(ui64 start, TMsgBunch* backLink) {
  156. AtomicSet(FirstSlot, start);
  157. memset(&LinkArray, 0, sizeof(LinkArray));
  158. AtomicSet(NextBunch, nullptr);
  159. AtomicSet(BackLink, backLink);
  160. AtomicSet(Token, 1);
  161. AtomicSet(NextToken, nullptr);
  162. }
  163. static void Release(TMsgBunch* block) {
  164. auto backLink = AtomicGet(block->BackLink);
  165. if (backLink == nullptr) {
  166. return;
  167. }
  168. AtomicSet(block->BackLink, nullptr);
  169. do {
  170. auto bbackLink = backLink->BackLink;
  171. delete backLink;
  172. backLink = bbackLink;
  173. } while (backLink != nullptr);
  174. }
  175. void Destroy() {
  176. for (auto tail = BackLink; tail != nullptr;) {
  177. auto next = tail->BackLink;
  178. delete tail;
  179. tail = next;
  180. }
  181. for (auto next = this; next != nullptr;) {
  182. auto nnext = next->NextBunch;
  183. delete next;
  184. next = nnext;
  185. }
  186. }
  187. };
  188. template <ui32 BUNCH_SIZE = DEFAULT_BUNCH_SIZE,
  189. typename TBunchBase = NReadAsFilledPrivate::TEmpty,
  190. typename TAux = TEmptyAux>
  191. class TWriteBucket {
  192. public:
  193. using TUsingAux = TAux; // for TReadBucket binding
  194. using TBunch = TMsgBunch<BUNCH_SIZE, TBunchBase, TAux>;
  195. TWriteBucket(TBunch* bunch = new TBunch(0, nullptr)) {
  196. AtomicSet(LastBunch, bunch);
  197. AtomicSet(SlotCounter, 0);
  198. }
  199. TWriteBucket(TWriteBucket&& move)
  200. : LastBunch(move.LastBunch)
  201. , SlotCounter(move.SlotCounter)
  202. {
  203. move.LastBunch = nullptr;
  204. }
  205. ~TWriteBucket() {
  206. if (LastBunch != nullptr) {
  207. LastBunch->Destroy();
  208. }
  209. }
  210. inline void Push(TMsgLink msg, TAux aux) {
  211. ui64 pushSlot = AtomicGetAndIncrement(SlotCounter);
  212. TBunch* hintBunch = GetLastBunch();
  213. for (;;) {
  214. auto hint = hintBunch->Push(msg, pushSlot, aux);
  215. if (Y_LIKELY(hint == PUSH_RESULT_OK)) {
  216. return;
  217. }
  218. HandleHint(hintBunch, hint);
  219. }
  220. }
  221. protected:
  222. template <typename, template <typename, typename...> class>
  223. friend class TReadBucket;
  224. TBunch* volatile LastBunch; // Hint
  225. volatile ui64 SlotCounter;
  226. inline TBunch* GetLastBunch() const {
  227. return AtomicGet(LastBunch);
  228. }
  229. void HandleHint(TBunch*& hintBunch, TPushResult hint) {
  230. if (Y_UNLIKELY(hint == PUSH_RESULT_BACKWARD)) {
  231. hintBunch = hintBunch->GetBackLink();
  232. return;
  233. }
  234. // PUSH_RESULT_FORWARD
  235. auto nextBunch = hintBunch->GetNextBunch();
  236. if (nextBunch == nullptr) {
  237. auto first = hintBunch->FirstSlot + BUNCH_SIZE;
  238. nextBunch = new TBunch(first, hintBunch);
  239. if (Y_UNLIKELY(!hintBunch->SetNextBunch(nextBunch))) {
  240. delete nextBunch;
  241. nextBunch = hintBunch->GetNextBunch();
  242. }
  243. }
  244. // hintBunch could not be freed here so it cannot be reused
  245. // it's alright if this CAS was not succeeded,
  246. // it means that other thread did that recently
  247. AtomicCas(&LastBunch, nextBunch, hintBunch);
  248. hintBunch = nextBunch;
  249. }
  250. };
  251. template <typename TWBucket = TWriteBucket<>,
  252. template <typename, typename...> class TContainer = TDeque>
  253. class TReadBucket {
  254. public:
  255. using TAux = typename TWBucket::TUsingAux;
  256. using TBunch = typename TWBucket::TBunch;
  257. static constexpr int MAX_NUMBER_OF_TRIES_TO_READ = 5;
  258. TReadBucket(TWBucket* writer)
  259. : Writer(writer)
  260. , ReadBunch(writer->GetLastBunch())
  261. , LastKnownPushBunch(writer->GetLastBunch())
  262. {
  263. ReadBunch->DecrementToken(); // no previous token
  264. }
  265. TReadBucket(TReadBucket toCopy, TWBucket* writer)
  266. : TReadBucket(std::move(toCopy))
  267. {
  268. Writer = writer;
  269. }
  270. ui64 ReadyCount() const {
  271. return AtomicGet(Writer->SlotCounter) - ReadSlot;
  272. }
  273. TMsgLink Pop() {
  274. return PopAux().Msg;
  275. }
  276. TMsgLink Peek() {
  277. return PeekAux().Msg;
  278. }
  279. TSlot<TAux> PopAux() {
  280. for (;;) {
  281. if (Y_UNLIKELY(ReadNow.size() != 0)) {
  282. auto result = PopSkipped();
  283. if (Y_LIKELY(result.Msg != nullptr)) {
  284. return result;
  285. }
  286. }
  287. if (Y_UNLIKELY(ReadSlot == LastKnownPushSlot)) {
  288. if (Y_LIKELY(!RereadPushSlot())) {
  289. return TSlot<TAux>::NullElem();
  290. }
  291. continue;
  292. }
  293. if (Y_UNLIKELY(!ReadBunch->IsSlotHere(ReadSlot))) {
  294. if (Y_UNLIKELY(!SwitchToNextBunch())) {
  295. return TSlot<TAux>::NullElem();
  296. }
  297. }
  298. auto result = ReadBunch->GetSlotAux(ReadSlot);
  299. if (Y_LIKELY(result.Msg != nullptr)) {
  300. ++ReadSlot;
  301. return result;
  302. }
  303. result = StubbornPop();
  304. if (Y_LIKELY(result.Msg != nullptr)) {
  305. return result;
  306. }
  307. }
  308. }
  309. TSlot<TAux> PeekAux() {
  310. for (;;) {
  311. if (Y_UNLIKELY(ReadNow.size() != 0)) {
  312. auto result = PeekSkipped();
  313. if (Y_LIKELY(result.Msg != nullptr)) {
  314. return result;
  315. }
  316. }
  317. if (Y_UNLIKELY(ReadSlot == LastKnownPushSlot)) {
  318. if (Y_LIKELY(!RereadPushSlot())) {
  319. return TSlot<TAux>::NullElem();
  320. }
  321. continue;
  322. }
  323. if (Y_UNLIKELY(!ReadBunch->IsSlotHere(ReadSlot))) {
  324. if (Y_UNLIKELY(!SwitchToNextBunch())) {
  325. return TSlot<TAux>::NullElem();
  326. }
  327. }
  328. auto result = ReadBunch->GetSlotAux(ReadSlot);
  329. if (Y_LIKELY(result.Msg != nullptr)) {
  330. return result;
  331. }
  332. result = StubbornPeek();
  333. if (Y_LIKELY(result.Msg != nullptr)) {
  334. return result;
  335. }
  336. }
  337. }
  338. private:
  339. TWBucket* Writer;
  340. TBunch* ReadBunch;
  341. ui64 ReadSlot = 0;
  342. TBunch* LastKnownPushBunch;
  343. ui64 LastKnownPushSlot = 0;
  344. struct TSkipItem {
  345. TBunch* Bunch;
  346. ui64 Slot;
  347. TBunch* Token;
  348. };
  349. TContainer<TSkipItem> ReadNow;
  350. TContainer<TSkipItem> ReadLater;
  351. void AddToReadLater() {
  352. ReadLater.push_back({ReadBunch, ReadSlot, LastKnownPushBunch});
  353. LastKnownPushBunch->IncrementToken();
  354. ++ReadSlot;
  355. }
  356. // MUST BE: ReadSlot == LastKnownPushSlot
  357. bool RereadPushSlot() {
  358. ReadNow = std::move(ReadLater);
  359. ReadLater.clear();
  360. auto oldSlot = LastKnownPushSlot;
  361. auto currentPushBunch = Writer->GetLastBunch();
  362. auto currentPushSlot = AtomicGet(Writer->SlotCounter);
  363. if (currentPushBunch != LastKnownPushBunch) {
  364. // LastKnownPushBunch could be invalid after this line
  365. LastKnownPushBunch->SetNextToken(currentPushBunch);
  366. }
  367. LastKnownPushBunch = currentPushBunch;
  368. LastKnownPushSlot = currentPushSlot;
  369. return oldSlot != LastKnownPushSlot;
  370. }
  371. bool SwitchToNextBunch() {
  372. for (int q = 0; q < MAX_NUMBER_OF_TRIES_TO_READ; ++q) {
  373. auto next = ReadBunch->GetNextBunch();
  374. if (next != nullptr) {
  375. ReadBunch = next;
  376. return true;
  377. }
  378. SpinLockPause();
  379. }
  380. return false;
  381. }
  382. TSlot<TAux> StubbornPop() {
  383. for (int q = 0; q < MAX_NUMBER_OF_TRIES_TO_READ; ++q) {
  384. auto result = ReadBunch->GetSlotAux(ReadSlot);
  385. if (Y_LIKELY(result.Msg != nullptr)) {
  386. ++ReadSlot;
  387. return result;
  388. }
  389. SpinLockPause();
  390. }
  391. AddToReadLater();
  392. return TSlot<TAux>::NullElem();
  393. }
  394. TSlot<TAux> StubbornPeek() {
  395. for (int q = 0; q < MAX_NUMBER_OF_TRIES_TO_READ; ++q) {
  396. auto result = ReadBunch->GetSlotAux(ReadSlot);
  397. if (Y_LIKELY(result.Msg != nullptr)) {
  398. return result;
  399. }
  400. SpinLockPause();
  401. }
  402. AddToReadLater();
  403. return TSlot<TAux>::NullElem();
  404. }
  405. TSlot<TAux> PopSkipped() {
  406. do {
  407. auto elem = ReadNow.front();
  408. ReadNow.pop_front();
  409. auto result = elem.Bunch->GetSlotAux(elem.Slot);
  410. if (Y_LIKELY(result.Msg != nullptr)) {
  411. elem.Token->DecrementToken();
  412. return result;
  413. }
  414. ReadLater.emplace_back(elem);
  415. } while (ReadNow.size() > 0);
  416. return TSlot<TAux>::NullElem();
  417. }
  418. TSlot<TAux> PeekSkipped() {
  419. do {
  420. auto elem = ReadNow.front();
  421. auto result = elem.Bunch->GetSlotAux(elem.Slot);
  422. if (Y_LIKELY(result.Msg != nullptr)) {
  423. return result;
  424. }
  425. ReadNow.pop_front();
  426. ReadLater.emplace_back(elem);
  427. } while (ReadNow.size() > 0);
  428. return TSlot<TAux>::NullElem();
  429. }
  430. };
  431. struct TDefaultParams {
  432. static constexpr ui32 BUNCH_SIZE = DEFAULT_BUNCH_SIZE;
  433. using TBunchBase = TEmpty;
  434. template <typename TElem, typename... TRest>
  435. using TContainer = TDeque<TElem, TRest...>;
  436. static constexpr bool DeleteItems = true;
  437. };
  438. } //namespace NReadAsFilledPrivate
  439. DeclareTuneValueParam(TRaFQueueBunchSize, ui32, BUNCH_SIZE);
  440. DeclareTuneTypeParam(TRaFQueueBunchBase, TBunchBase);
  441. DeclareTuneContainer(TRaFQueueSkipContainer, TContainer);
  442. DeclareTuneValueParam(TRaFQueueDeleteItems, bool, DeleteItems);
  443. template <typename TItem = void, typename... TParams>
  444. class TReadAsFilledQueue {
  445. private:
  446. using TTuned = TTune<NReadAsFilledPrivate::TDefaultParams, TParams...>;
  447. static constexpr ui32 BUNCH_SIZE = TTuned::BUNCH_SIZE;
  448. using TBunchBase = typename TTuned::TBunchBase;
  449. template <typename TElem, typename... TRest>
  450. using TContainer =
  451. typename TTuned::template TContainer<TElem, TRest...>;
  452. using TWriteBucket =
  453. NReadAsFilledPrivate::TWriteBucket<BUNCH_SIZE, TBunchBase>;
  454. using TReadBucket =
  455. NReadAsFilledPrivate::TReadBucket<TWriteBucket, TContainer>;
  456. public:
  457. TReadAsFilledQueue()
  458. : RBucket(&WBucket)
  459. {
  460. }
  461. ~TReadAsFilledQueue() {
  462. if (TTuned::DeleteItems) {
  463. for (;;) {
  464. auto msg = Pop();
  465. if (msg == nullptr) {
  466. break;
  467. }
  468. TDelete::Destroy(msg);
  469. }
  470. }
  471. }
  472. void Push(TItem* msg) {
  473. WBucket.Push((void*)msg, NReadAsFilledPrivate::TEmptyAux());
  474. }
  475. TItem* Pop() {
  476. return (TItem*)RBucket.Pop();
  477. }
  478. TItem* Peek() {
  479. return (TItem*)RBucket.Peek();
  480. }
  481. protected:
  482. TWriteBucket WBucket;
  483. TReadBucket RBucket;
  484. };
  485. }