Debian Codegraph @

src/dmlc-core/include/dmlc/blockingconcurrentqueue.h

raw symbols SCIP
1 //! \cond Doxygen_Suppress
2 // Provides an efficient blocking version of moodycamel::ConcurrentQueue.
3 // ©2015-2016 Cameron Desrochers. Distributed under the terms of the simplified
4 // BSD license, available at the top of concurrentqueue.h.
5 // Uses Jeff Preshing's semaphore implementation (under the terms of its
6 // separate zlib license, embedded below).
7
8 #ifndef DMLC_BLOCKINGCONCURRENTQUEUE_H_
9 #define DMLC_BLOCKINGCONCURRENTQUEUE_H_
10
11 #pragma once
12
13 #include <cerrno>
14 #include <chrono>
15 #include <ctime>
16 #include <memory>
17 #include <type_traits>
18
19 #include "concurrentqueue.h"
20
21 #if defined(_WIN32)
22 // Avoid including windows.h in a header; we only need a handful of
23 // items, so we'll redeclare them here (this is relatively safe since
24 // the API generally has to remain stable between Windows versions).
25 // I know this is an ugly hack but it still beats polluting the global
26 // namespace with thousands of generic names or adding a .cpp for nothing.
27 extern "C" {
28 struct _SECURITY_ATTRIBUTES;
29 __declspec(dllimport) void *__stdcall CreateSemaphoreW(_SECURITY_ATTRIBUTES *lpSemaphoreAttributes,
30 long lInitialCount, long lMaximumCount, const wchar_t *lpName);
31 __declspec(dllimport) int __stdcall CloseHandle(void *hObject);
32 __declspec(dllimport) unsigned long __stdcall WaitForSingleObject(
33 void *hHandle, unsigned long dwMilliseconds);
34 __declspec(dllimport) int __stdcall ReleaseSemaphore(
35 void *hSemaphore, long lReleaseCount, long *lpPreviousCount);
36 }
37 #elif defined(__MACH__)
38 #include <mach/mach.h>
39 #elif defined(__unix__)
40 #include <semaphore.h>
41 #endif
42
43 namespace dmlc {
44
45 namespace moodycamel {
46 namespace details {
47 // Code in the mpmc_sema namespace below is an adaptation of Jeff Preshing's
48 // portable + lightweight semaphore implementations, originally from
49 // https://github.com/preshing/cpp11-on-multicore/blob/master/common/sema.h
50 // LICENSE:
51 // Copyright (c) 2015 Jeff Preshing
52 //
53 // This software is provided 'as-is', without any express or implied
54 // warranty. In no event will the authors be held liable for any damages
55 // arising from the use of this software.
56 //
57 // Permission is granted to anyone to use this software for any purpose,
58 // including commercial applications, and to alter it and redistribute it
59 // freely, subject to the following restrictions:
60 //
61 // 1. The origin of this software must not be misrepresented; you must not
62 // claim that you wrote the original software. If you use this software
63 // in a product, an acknowledgement in the product documentation would be
64 // appreciated but is not required.
65 // 2. Altered source versions must be plainly marked as such, and must not be
66 // misrepresented as being the original software.
67 // 3. This notice may not be removed or altered from any source distribution.
68 namespace mpmc_sema {
69 #if defined(_WIN32)
70 class Semaphore {
71 private:
72 void *m_hSema;
73
74 Semaphore(const Semaphore &other) MOODYCAMEL_DELETE_FUNCTION;
75 Semaphore &operator=(const Semaphore &other) MOODYCAMEL_DELETE_FUNCTION;
76
77 public:
78 Semaphore(int initialCount = 0) {
79 assert(initialCount >= 0);
80 const long maxLong = 0x7fffffff;
81 m_hSema = CreateSemaphoreW(nullptr, initialCount, maxLong, nullptr);
82 }
83
84 ~Semaphore() {
85 CloseHandle(m_hSema);
86 }
87
88 void wait() {
89 const unsigned long infinite = 0xffffffff;
90 WaitForSingleObject(m_hSema, infinite);
91 }
92
93 bool try_wait() {
94 const unsigned long RC_WAIT_TIMEOUT = 0x00000102;
95 return WaitForSingleObject(m_hSema, 0) != RC_WAIT_TIMEOUT;
96 }
97
98 bool timed_wait(std::uint64_t usecs) {
99 const unsigned long RC_WAIT_TIMEOUT = 0x00000102;
100 return WaitForSingleObject(m_hSema, (unsigned long)(usecs / 1000)) != RC_WAIT_TIMEOUT;
101 }
102
103 void signal(int count = 1) {
104 ReleaseSemaphore(m_hSema, count, nullptr);
105 }
106 };
107 #elif defined(__MACH__)
108 //---------------------------------------------------------
109 // Semaphore (Apple iOS and OSX)
110 // Can't use POSIX semaphores due to
111 // http://lists.apple.com/archives/darwin-kernel/2009/Apr/msg00010.html
112 //---------------------------------------------------------
113 class Semaphore {
114 private:
115 semaphore_t m_sema;
116
117 Semaphore(const Semaphore &other) MOODYCAMEL_DELETE_FUNCTION;
118 Semaphore &operator=(const Semaphore &other) MOODYCAMEL_DELETE_FUNCTION;
119
120 public:
121 Semaphore(int initialCount = 0) {
122 assert(initialCount >= 0);
123 semaphore_create(mach_task_self(), &m_sema, SYNC_POLICY_FIFO, initialCount);
124 }
125
126 ~Semaphore() {
127 semaphore_destroy(mach_task_self(), m_sema);
128 }
129
130 void wait() {
131 semaphore_wait(m_sema);
132 }
133
134 bool try_wait() {
135 return timed_wait(0);
136 }
137
138 bool timed_wait(std::uint64_t timeout_usecs) {
139 mach_timespec_t ts;
140 ts.tv_sec = static_cast<unsigned int>(timeout_usecs / 1000000);
141 ts.tv_nsec = (timeout_usecs % 1000000) * 1000;
142
143 // added in OSX 10.10:
144 // https://developer.apple.com/library/prerelease/mac/documentation/General/Reference/APIDiffsMacOSX10_10SeedDiff/modules/Darwin.html
145 kern_return_t rc = semaphore_timedwait(m_sema, ts);
146
147 return rc != KERN_OPERATION_TIMED_OUT;
148 }
149
150 void signal() {
151 semaphore_signal(m_sema);
152 }
153
154 void signal(int count) {
155 while (count-- > 0) {
156 semaphore_signal(m_sema);
157 }
158 }
159 };
160 #elif defined(__unix__)
161 //---------------------------------------------------------
162 // Semaphore (POSIX, Linux)
163 //---------------------------------------------------------
164 class Semaphore {
165 private:
166 sem_t m_sema;
167
168 Semaphore(const Semaphore &other) MOODYCAMEL_DELETE_FUNCTION;
169 Semaphore &operator=(const Semaphore &other) MOODYCAMEL_DELETE_FUNCTION;
170
171 public:
172 Semaphore(int initialCount = 0) {
173 assert(initialCount >= 0);
174 sem_init(&m_sema, 0, initialCount);
175 }
176
177 ~Semaphore() {
178 sem_destroy(&m_sema);
179 }
180
181 void wait() {
182 // http://stackoverflow.com/questions/2013181/gdb-causes-sem-wait-to-fail-with-eintr-error
183 int rc;
184 do {
185 rc = sem_wait(&m_sema);
186 } while (rc == -1 && errno == EINTR);
187 }
188
189 bool try_wait() {
190 int rc;
191 do {
192 rc = sem_trywait(&m_sema);
193 } while (rc == -1 && errno == EINTR);
194 return !(rc == -1 && errno == EAGAIN);
195 }
196
197 bool timed_wait(std::uint64_t usecs) {
198 struct timespec ts;
199 const int usecs_in_1_sec = 1000000;
200 const int nsecs_in_1_sec = 1000000000;
201 clock_gettime(CLOCK_REALTIME, &ts);
202 ts.tv_sec += usecs / usecs_in_1_sec;
203 ts.tv_nsec += (usecs % usecs_in_1_sec) * 1000;
204 // sem_timedwait bombs if you have more than 1e9 in tv_nsec
205 // so we have to clean things up before passing it in
206 if (ts.tv_nsec >= nsecs_in_1_sec) {
207 ts.tv_nsec -= nsecs_in_1_sec;
208 ++ts.tv_sec;
209 }
210
211 int rc;
212 do {
213 rc = sem_timedwait(&m_sema, &ts);
214 } while (rc == -1 && errno == EINTR);
215 return !(rc == -1 && errno == ETIMEDOUT);
216 }
217
218 void signal() {
219 sem_post(&m_sema);
220 }
221
222 void signal(int count) {
223 while (count-- > 0) {
224 sem_post(&m_sema);
225 }
226 }
227 };
228 #else
229 #error Unsupported platform! (No semaphore wrapper available)
230 #endif
231
232 //---------------------------------------------------------
233 // LightweightSemaphore
234 //---------------------------------------------------------
235 class LightweightSemaphore {
236 public:
237 typedef std::make_signed<std::size_t>::type ssize_t;
238
239 private:
240 std::atomic<ssize_t> m_count;
241 Semaphore m_sema;
242
243 bool waitWithPartialSpinning(std::int64_t timeout_usecs = -1) {
244 ssize_t oldCount;
245 // Is there a better way to set the initial spin count?
246 // If we lower it to 1000, testBenaphore becomes 15x slower on my Core i7-5930K Windows PC,
247 // as threads start hitting the kernel semaphore.
248 int spin = 10000;
249 while (--spin >= 0) {
250 oldCount = m_count.load(std::memory_order_relaxed);
251 if ((oldCount > 0)
252 && m_count.compare_exchange_strong(
253 oldCount, oldCount - 1, std::memory_order_acquire, std::memory_order_relaxed)) {
254 return true;
255 }
256 std::atomic_signal_fence(
257 std::memory_order_acquire); // Prevent the compiler from collapsing the loop.
258 }
259 oldCount = m_count.fetch_sub(1, std::memory_order_acquire);
260 if (oldCount > 0) {
261 return true;
262 }
263 if (timeout_usecs < 0) {
264 m_sema.wait();
265 return true;
266 }
267 if (m_sema.timed_wait((std::uint64_t)timeout_usecs)) {
268 return true;
269 }
270 // At this point, we've timed out waiting for the semaphore, but the
271 // count is still decremented indicating we may still be waiting on
272 // it. So we have to re-adjust the count, but only if the semaphore
273 // wasn't signaled enough times for us too since then. If it was, we
274 // need to release the semaphore too.
275 while (true) {
276 oldCount = m_count.load(std::memory_order_acquire);
277 if (oldCount >= 0 && m_sema.try_wait()) {
278 return true;
279 }
280 if (oldCount < 0
281 && m_count.compare_exchange_strong(
282 oldCount, oldCount + 1, std::memory_order_relaxed, std::memory_order_relaxed)) {
283 return false;
284 }
285 }
286 }
287
288 ssize_t waitManyWithPartialSpinning(ssize_t max, std::int64_t timeout_usecs = -1) {
289 assert(max > 0);
290 ssize_t oldCount;
291 int spin = 10000;
292 while (--spin >= 0) {
293 oldCount = m_count.load(std::memory_order_relaxed);
294 if (oldCount > 0) {
295 ssize_t newCount = oldCount > max ? oldCount - max : 0;
296 if (m_count.compare_exchange_strong(
297 oldCount, newCount, std::memory_order_acquire, std::memory_order_relaxed)) {
298 return oldCount - newCount;
299 }
300 }
301 std::atomic_signal_fence(std::memory_order_acquire);
302 }
303 oldCount = m_count.fetch_sub(1, std::memory_order_acquire);
304 if (oldCount <= 0) {
305 if (timeout_usecs < 0) {
306 m_sema.wait();
307 } else if (!m_sema.timed_wait((std::uint64_t)timeout_usecs)) {
308 while (true) {
309 oldCount = m_count.load(std::memory_order_acquire);
310 if (oldCount >= 0 && m_sema.try_wait()) {
311 break;
312 }
313 if (oldCount < 0
314 && m_count.compare_exchange_strong(
315 oldCount, oldCount + 1, std::memory_order_relaxed, std::memory_order_relaxed)) {
316 return 0;
317 }
318 }
319 }
320 }
321 if (max > 1) {
322 return 1 + tryWaitMany(max - 1);
323 }
324 return 1;
325 }
326
327 public:
328 LightweightSemaphore(ssize_t initialCount = 0) : m_count(initialCount) {
329 assert(initialCount >= 0);
330 }
331
332 bool tryWait() {
333 ssize_t oldCount = m_count.load(std::memory_order_relaxed);
334 while (oldCount > 0) {
335 if (m_count.compare_exchange_weak(
336 oldCount, oldCount - 1, std::memory_order_acquire, std::memory_order_relaxed)) {
337 return true;
338 }
339 }
340 return false;
341 }
342
343 void wait() {
344 if (!tryWait()) {
345 waitWithPartialSpinning();
346 }
347 }
348
349 bool wait(std::int64_t timeout_usecs) {
350 return tryWait() || waitWithPartialSpinning(timeout_usecs);
351 }
352
353 // Acquires between 0 and (greedily) max, inclusive
354 ssize_t tryWaitMany(ssize_t max) {
355 assert(max >= 0);
356 ssize_t oldCount = m_count.load(std::memory_order_relaxed);
357 while (oldCount > 0) {
358 ssize_t newCount = oldCount > max ? oldCount - max : 0;
359 if (m_count.compare_exchange_weak(
360 oldCount, newCount, std::memory_order_acquire, std::memory_order_relaxed)) {
361 return oldCount - newCount;
362 }
363 }
364 return 0;
365 }
366
367 // Acquires at least one, and (greedily) at most max
368 ssize_t waitMany(ssize_t max, std::int64_t timeout_usecs) {
369 assert(max >= 0);
370 ssize_t result = tryWaitMany(max);
371 if (result == 0 && max > 0) {
372 result = waitManyWithPartialSpinning(max, timeout_usecs);
373 }
374 return result;
375 }
376
377 ssize_t waitMany(ssize_t max) {
378 ssize_t result = waitMany(max, -1);
379 assert(result > 0);
380 return result;
381 }
382
383 void signal(ssize_t count = 1) {
384 assert(count >= 0);
385 ssize_t oldCount = m_count.fetch_add(count, std::memory_order_release);
386 ssize_t toRelease = -oldCount < count ? -oldCount : count;
387 if (toRelease > 0) {
388 m_sema.signal((int)toRelease);
389 }
390 }
391
392 ssize_t availableApprox() const {
393 ssize_t count = m_count.load(std::memory_order_relaxed);
394 return count > 0 ? count : 0;
395 }
396 };
397 } // end namespace mpmc_sema
398 } // end namespace details
399
400 // This is a blocking version of the queue. It has an almost identical interface to
401 // the normal non-blocking version, with the addition of various wait_dequeue() methods
402 // and the removal of producer-specific dequeue methods.
403 template <typename T, typename Traits = ConcurrentQueueDefaultTraits>
404 class BlockingConcurrentQueue {
405 private:
406 typedef ::dmlc::moodycamel::ConcurrentQueue<T, Traits> ConcurrentQueue;
407 typedef details::mpmc_sema::LightweightSemaphore LightweightSemaphore;
408
409 public:
410 typedef typename ConcurrentQueue::producer_token_t producer_token_t;
411 typedef typename ConcurrentQueue::consumer_token_t consumer_token_t;
412
413 typedef typename ConcurrentQueue::index_t index_t;
414 typedef typename ConcurrentQueue::size_t size_t;
415 typedef typename std::make_signed<size_t>::type ssize_t;
416
417 static const size_t BLOCK_SIZE = ConcurrentQueue::BLOCK_SIZE;
418 static const size_t EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD
419 = ConcurrentQueue::EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD;
420 static const size_t EXPLICIT_INITIAL_INDEX_SIZE = ConcurrentQueue::EXPLICIT_INITIAL_INDEX_SIZE;
421 static const size_t IMPLICIT_INITIAL_INDEX_SIZE = ConcurrentQueue::IMPLICIT_INITIAL_INDEX_SIZE;
422 static const size_t INITIAL_IMPLICIT_PRODUCER_HASH_SIZE
423 = ConcurrentQueue::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE;
424 static const std::uint32_t EXPLICIT_CONSUMER_CONSUMPTION_QUOTA_BEFORE_ROTATE
425 = ConcurrentQueue::EXPLICIT_CONSUMER_CONSUMPTION_QUOTA_BEFORE_ROTATE;
426 static const size_t MAX_SUBQUEUE_SIZE = ConcurrentQueue::MAX_SUBQUEUE_SIZE;
427
428 public:
429 // Creates a queue with at least `capacity` element slots; note that the
430 // actual number of elements that can be inserted without additional memory
431 // allocation depends on the number of producers and the block size (e.g. if
432 // the block size is equal to `capacity`, only a single block will be allocated
433 // up-front, which means only a single producer will be able to enqueue elements
434 // without an extra allocation -- blocks aren't shared between producers).
435 // This method is not thread safe -- it is up to the user to ensure that the
436 // queue is fully constructed before it starts being used by other threads (this
437 // includes making the memory effects of construction visible, possibly with a
438 // memory barrier).
439 explicit BlockingConcurrentQueue(size_t capacity = 6 * BLOCK_SIZE)
440 : inner(capacity),
441 sema(create<LightweightSemaphore>(),
442 &BlockingConcurrentQueue::template destroy<LightweightSemaphore>) {
443 assert(reinterpret_cast<ConcurrentQueue *>((BlockingConcurrentQueue *)1)
444 == &((BlockingConcurrentQueue *)1)->inner
445 && "BlockingConcurrentQueue must have ConcurrentQueue as its first member");
446 if (!sema) {
447 MOODYCAMEL_THROW(std::bad_alloc());
448 }
449 }
450
451 BlockingConcurrentQueue(
452 size_t minCapacity, size_t maxExplicitProducers, size_t maxImplicitProducers)
453 : inner(minCapacity, maxExplicitProducers, maxImplicitProducers),
454 sema(create<LightweightSemaphore>(),
455 &BlockingConcurrentQueue::template destroy<LightweightSemaphore>) {
456 assert(reinterpret_cast<ConcurrentQueue *>((BlockingConcurrentQueue *)1)
457 == &((BlockingConcurrentQueue *)1)->inner
458 && "BlockingConcurrentQueue must have ConcurrentQueue as its first member");
459 if (!sema) {
460 MOODYCAMEL_THROW(std::bad_alloc());
461 }
462 }
463
464 // Disable copying and copy assignment
465 BlockingConcurrentQueue(const BlockingConcurrentQueue &) MOODYCAMEL_DELETE_FUNCTION;
466 BlockingConcurrentQueue &operator=(const BlockingConcurrentQueue &) MOODYCAMEL_DELETE_FUNCTION;
467
468 // Moving is supported, but note that it is *not* a thread-safe operation.
469 // Nobody can use the queue while it's being moved, and the memory effects
470 // of that move must be propagated to other threads before they can use it.
471 // Note: When a queue is moved, its tokens are still valid but can only be
472 // used with the destination queue (i.e. semantically they are moved along
473 // with the queue itself).
474 BlockingConcurrentQueue(BlockingConcurrentQueue &&other) MOODYCAMEL_NOEXCEPT :
475 inner(std::move(other.inner)),
476 sema(std::move(other.sema)) {}
477
478 inline BlockingConcurrentQueue &operator=(BlockingConcurrentQueue &&other) MOODYCAMEL_NOEXCEPT {
479 return swap_internal(other);
480 }
481
482 // Swaps this queue's state with the other's. Not thread-safe.
483 // Swapping two queues does not invalidate their tokens, however
484 // the tokens that were created for one queue must be used with
485 // only the swapped queue (i.e. the tokens are tied to the
486 // queue's movable state, not the object itself).
487 inline void swap(BlockingConcurrentQueue &other) MOODYCAMEL_NOEXCEPT {
488 swap_internal(other);
489 }
490
491 private:
492 BlockingConcurrentQueue &swap_internal(BlockingConcurrentQueue &other) {
493 if (this == &other) {
494 return *this;
495 }
496
497 inner.swap(other.inner);
498 sema.swap(other.sema);
499 return *this;
500 }
501
502 public:
503 // Enqueues a single item (by copying it).
504 // Allocates memory if required. Only fails if memory allocation fails (or implicit
505 // production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0,
506 // or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
507 // Thread-safe.
508 inline bool enqueue(const T &item) {
509 if (details::likely(inner.enqueue(item))) {
510 sema->signal();
511 return true;
512 }
513 return false;
514 }
515
516 // Enqueues a single item (by moving it, if possible).
517 // Allocates memory if required. Only fails if memory allocation fails (or implicit
518 // production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0,
519 // or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
520 // Thread-safe.
521 inline bool enqueue(T &&item) {
522 if (details::likely(inner.enqueue(std::move(item)))) {
523 sema->signal();
524 return true;
525 }
526 return false;
527 }
528
529 // Enqueues a single item (by copying it) using an explicit producer token.
530 // Allocates memory if required. Only fails if memory allocation fails (or
531 // Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
532 // Thread-safe.
533 inline bool enqueue(const producer_token_t &token, const T &item) {
534 if (details::likely(inner.enqueue(token, item))) {
535 sema->signal();
536 return true;
537 }
538 return false;
539 }
540
541 // Enqueues a single item (by moving it, if possible) using an explicit producer token.
542 // Allocates memory if required. Only fails if memory allocation fails (or
543 // Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
544 // Thread-safe.
545 inline bool enqueue(const producer_token_t &token, T &&item) {
546 if (details::likely(inner.enqueue(token, std::move(item)))) {
547 sema->signal();
548 return true;
549 }
550 return false;
551 }
552
553 // Enqueues several items.
554 // Allocates memory if required. Only fails if memory allocation fails (or
555 // implicit production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE
556 // is 0, or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
557 // Note: Use std::make_move_iterator if the elements should be moved instead of copied.
558 // Thread-safe.
559 template <typename It>
560 inline bool enqueue_bulk(It itemFirst, size_t count) {
561 if (details::likely(inner.enqueue_bulk(std::forward<It>(itemFirst), count))) {
562 sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count);
563 return true;
564 }
565 return false;
566 }
567
568 // Enqueues several items using an explicit producer token.
569 // Allocates memory if required. Only fails if memory allocation fails
570 // (or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
571 // Note: Use std::make_move_iterator if the elements should be moved
572 // instead of copied.
573 // Thread-safe.
574 template <typename It>
575 inline bool enqueue_bulk(const producer_token_t &token, It itemFirst, size_t count) {
576 if (details::likely(inner.enqueue_bulk(token, std::forward<It>(itemFirst), count))) {
577 sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count);
578 return true;
579 }
580 return false;
581 }
582
583 // Enqueues a single item (by copying it).
584 // Does not allocate memory. Fails if not enough room to enqueue (or implicit
585 // production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE
586 // is 0).
587 // Thread-safe.
588 inline bool try_enqueue(const T &item) {
589 if (inner.try_enqueue(item)) {
590 sema->signal();
591 return true;
592 }
593 return false;
594 }
595
596 // Enqueues a single item (by moving it, if possible).
597 // Does not allocate memory (except for one-time implicit producer).
598 // Fails if not enough room to enqueue (or implicit production is
599 // disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0).
600 // Thread-safe.
601 inline bool try_enqueue(T &&item) {
602 if (inner.try_enqueue(std::move(item))) {
603 sema->signal();
604 return true;
605 }
606 return false;
607 }
608
609 // Enqueues a single item (by copying it) using an explicit producer token.
610 // Does not allocate memory. Fails if not enough room to enqueue.
611 // Thread-safe.
612 inline bool try_enqueue(const producer_token_t &token, const T &item) {
613 if (inner.try_enqueue(token, item)) {
614 sema->signal();
615 return true;
616 }
617 return false;
618 }
619
620 // Enqueues a single item (by moving it, if possible) using an explicit producer token.
621 // Does not allocate memory. Fails if not enough room to enqueue.
622 // Thread-safe.
623 inline bool try_enqueue(const producer_token_t &token, T &&item) {
624 if (inner.try_enqueue(token, std::move(item))) {
625 sema->signal();
626 return true;
627 }
628 return false;
629 }
630
631 // Enqueues several items.
632 // Does not allocate memory (except for one-time implicit producer).
633 // Fails if not enough room to enqueue (or implicit production is
634 // disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0).
635 // Note: Use std::make_move_iterator if the elements should be moved
636 // instead of copied.
637 // Thread-safe.
638 template <typename It>
639 inline bool try_enqueue_bulk(It itemFirst, size_t count) {
640 if (inner.try_enqueue_bulk(std::forward<It>(itemFirst), count)) {
641 sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count);
642 return true;
643 }
644 return false;
645 }
646
647 // Enqueues several items using an explicit producer token.
648 // Does not allocate memory. Fails if not enough room to enqueue.
649 // Note: Use std::make_move_iterator if the elements should be moved
650 // instead of copied.
651 // Thread-safe.
652 template <typename It>
653 inline bool try_enqueue_bulk(const producer_token_t &token, It itemFirst, size_t count) {
654 if (inner.try_enqueue_bulk(token, std::forward<It>(itemFirst), count)) {
655 sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count);
656 return true;
657 }
658 return false;
659 }
660
661 // Attempts to dequeue from the queue.
662 // Returns false if all producer streams appeared empty at the time they
663 // were checked (so, the queue is likely but not guaranteed to be empty).
664 // Never allocates. Thread-safe.
665 template <typename U>
666 inline bool try_dequeue(U &item) {
667 if (sema->tryWait()) {
668 while (!inner.try_dequeue(item)) {
669 continue;
670 }
671 return true;
672 }
673 return false;
674 }
675
676 // Attempts to dequeue from the queue using an explicit consumer token.
677 // Returns false if all producer streams appeared empty at the time they
678 // were checked (so, the queue is likely but not guaranteed to be empty).
679 // Never allocates. Thread-safe.
680 template <typename U>
681 inline bool try_dequeue(consumer_token_t &token, U &item) {
682 if (sema->tryWait()) {
683 while (!inner.try_dequeue(token, item)) {
684 continue;
685 }
686 return true;
687 }
688 return false;
689 }
690
691 // Attempts to dequeue several elements from the queue.
692 // Returns the number of items actually dequeued.
693 // Returns 0 if all producer streams appeared empty at the time they
694 // were checked (so, the queue is likely but not guaranteed to be empty).
695 // Never allocates. Thread-safe.
696 template <typename It>
697 inline size_t try_dequeue_bulk(It itemFirst, size_t max) {
698 size_t count = 0;
699 max = (size_t)sema->tryWaitMany((LightweightSemaphore::ssize_t)(ssize_t)max);
700 while (count != max) {
701 count += inner.template try_dequeue_bulk<It &>(itemFirst, max - count);
702 }
703 return count;
704 }
705
706 // Attempts to dequeue several elements from the queue using an explicit consumer token.
707 // Returns the number of items actually dequeued.
708 // Returns 0 if all producer streams appeared empty at the time they
709 // were checked (so, the queue is likely but not guaranteed to be empty).
710 // Never allocates. Thread-safe.
711 template <typename It>
712 inline size_t try_dequeue_bulk(consumer_token_t &token, It itemFirst, size_t max) {
713 size_t count = 0;
714 max = (size_t)sema->tryWaitMany((LightweightSemaphore::ssize_t)(ssize_t)max);
715 while (count != max) {
716 count += inner.template try_dequeue_bulk<It &>(token, itemFirst, max - count);
717 }
718 return count;
719 }
720
721 // Blocks the current thread until there's something to dequeue, then
722 // dequeues it.
723 // Never allocates. Thread-safe.
724 template <typename U>
725 inline void wait_dequeue(U &item) {
726 sema->wait();
727 while (!inner.try_dequeue(item)) {
728 continue;
729 }
730 }
731
732 // Blocks the current thread until either there's something to dequeue
733 // or the timeout (specified in microseconds) expires. Returns false
734 // without setting `item` if the timeout expires, otherwise assigns
735 // to `item` and returns true.
736 // Using a negative timeout indicates an indefinite timeout,
737 // and is thus functionally equivalent to calling wait_dequeue.
738 // Never allocates. Thread-safe.
739 template <typename U>
740 inline bool wait_dequeue_timed(U &item, std::int64_t timeout_usecs) {
741 if (!sema->wait(timeout_usecs)) {
742 return false;
743 }
744 while (!inner.try_dequeue(item)) {
745 continue;
746 }
747 return true;
748 }
749
750 // Blocks the current thread until either there's something to dequeue
751 // or the timeout expires. Returns false without setting `item` if the
752 // timeout expires, otherwise assigns to `item` and returns true.
753 // Never allocates. Thread-safe.
754 template <typename U, typename Rep, typename Period>
755 inline bool wait_dequeue_timed(U &item, const std::chrono::duration<Rep, Period> &timeout) {
756 return wait_dequeue_timed(
757 item, std::chrono::duration_cast<std::chrono::microseconds>(timeout).count());
758 }
759
760 // Blocks the current thread until there's something to dequeue, then
761 // dequeues it using an explicit consumer token.
762 // Never allocates. Thread-safe.
763 template <typename U>
764 inline void wait_dequeue(consumer_token_t &token, U &item) {
765 sema->wait();
766 while (!inner.try_dequeue(token, item)) {
767 continue;
768 }
769 }
770
771 // Blocks the current thread until either there's something to dequeue
772 // or the timeout (specified in microseconds) expires. Returns false
773 // without setting `item` if the timeout expires, otherwise assigns
774 // to `item` and returns true.
775 // Using a negative timeout indicates an indefinite timeout,
776 // and is thus functionally equivalent to calling wait_dequeue.
777 // Never allocates. Thread-safe.
778 template <typename U>
779 inline bool wait_dequeue_timed(consumer_token_t &token, U &item, std::int64_t timeout_usecs) {
780 if (!sema->wait(timeout_usecs)) {
781 return false;
782 }
783 while (!inner.try_dequeue(token, item)) {
784 continue;
785 }
786 return true;
787 }
788
789 // Blocks the current thread until either there's something to dequeue
790 // or the timeout expires. Returns false without setting `item` if the
791 // timeout expires, otherwise assigns to `item` and returns true.
792 // Never allocates. Thread-safe.
793 template <typename U, typename Rep, typename Period>
794 inline bool wait_dequeue_timed(
795 consumer_token_t &token, U &item, const std::chrono::duration<Rep, Period> &timeout) {
796 return wait_dequeue_timed(
797 token, item, std::chrono::duration_cast<std::chrono::microseconds>(timeout).count());
798 }
799
800 // Attempts to dequeue several elements from the queue.
801 // Returns the number of items actually dequeued, which will
802 // always be at least one (this method blocks until the queue
803 // is non-empty) and at most max.
804 // Never allocates. Thread-safe.
805 template <typename It>
806 inline size_t wait_dequeue_bulk(It itemFirst, size_t max) {
807 size_t count = 0;
808 max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max);
809 while (count != max) {
810 count += inner.template try_dequeue_bulk<It &>(itemFirst, max - count);
811 }
812 return count;
813 }
814
815 // Attempts to dequeue several elements from the queue.
816 // Returns the number of items actually dequeued, which can
817 // be 0 if the timeout expires while waiting for elements,
818 // and at most max.
819 // Using a negative timeout indicates an indefinite timeout,
820 // and is thus functionally equivalent to calling wait_dequeue_bulk.
821 // Never allocates. Thread-safe.
822 template <typename It>
823 inline size_t wait_dequeue_bulk_timed(It itemFirst, size_t max, std::int64_t timeout_usecs) {
824 size_t count = 0;
825 max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max, timeout_usecs);
826 while (count != max) {
827 count += inner.template try_dequeue_bulk<It &>(itemFirst, max - count);
828 }
829 return count;
830 }
831
832 // Attempts to dequeue several elements from the queue.
833 // Returns the number of items actually dequeued, which can
834 // be 0 if the timeout expires while waiting for elements,
835 // and at most max.
836 // Never allocates. Thread-safe.
837 template <typename It, typename Rep, typename Period>
838 inline size_t wait_dequeue_bulk_timed(
839 It itemFirst, size_t max, const std::chrono::duration<Rep, Period> &timeout) {
840 return wait_dequeue_bulk_timed<It &>(
841 itemFirst, max, std::chrono::duration_cast<std::chrono::microseconds>(timeout).count());
842 }
843
844 // Attempts to dequeue several elements from the queue using an explicit consumer token.
845 // Returns the number of items actually dequeued, which will
846 // always be at least one (this method blocks until the queue
847 // is non-empty) and at most max.
848 // Never allocates. Thread-safe.
849 template <typename It>
850 inline size_t wait_dequeue_bulk(consumer_token_t &token, It itemFirst, size_t max) {
851 size_t count = 0;
852 max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max);
853 while (count != max) {
854 count += inner.template try_dequeue_bulk<It &>(token, itemFirst, max - count);
855 }
856 return count;
857 }
858
859 // Attempts to dequeue several elements from the queue using an explicit consumer token.
860 // Returns the number of items actually dequeued, which can
861 // be 0 if the timeout expires while waiting for elements,
862 // and at most max.
863 // Using a negative timeout indicates an indefinite timeout,
864 // and is thus functionally equivalent to calling wait_dequeue_bulk.
865 // Never allocates. Thread-safe.
866 template <typename It>
867 inline size_t wait_dequeue_bulk_timed(
868 consumer_token_t &token, It itemFirst, size_t max, std::int64_t timeout_usecs) {
869 size_t count = 0;
870 max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max, timeout_usecs);
871 while (count != max) {
872 count += inner.template try_dequeue_bulk<It &>(token, itemFirst, max - count);
873 }
874 return count;
875 }
876
877 // Attempts to dequeue several elements from the queue using an explicit consumer token.
878 // Returns the number of items actually dequeued, which can
879 // be 0 if the timeout expires while waiting for elements,
880 // and at most max.
881 // Never allocates. Thread-safe.
882 template <typename It, typename Rep, typename Period>
883 inline size_t wait_dequeue_bulk_timed(consumer_token_t &token, It itemFirst, size_t max,
884 const std::chrono::duration<Rep, Period> &timeout) {
885 return wait_dequeue_bulk_timed<It &>(token, itemFirst, max,
886 std::chrono::duration_cast<std::chrono::microseconds>(timeout).count());
887 }
888
889 // Returns an estimate of the total number of elements currently in the queue. This
890 // estimate is only accurate if the queue has completely stabilized before it is called
891 // (i.e. all enqueue and dequeue operations have completed and their memory effects are
892 // visible on the calling thread, and no further operations start while this method is
893 // being called).
894 // Thread-safe.
895 inline size_t size_approx() const {
896 return (size_t)sema->availableApprox();
897 }
898
899 // Returns true if the underlying atomic variables used by
900 // the queue are lock-free (they should be on most platforms).
901 // Thread-safe.
902 static bool is_lock_free() {
903 return ConcurrentQueue::is_lock_free();
904 }
905
906 private:
907 template <typename U>
908 static inline U *create() {
909 auto p = (Traits::malloc)(sizeof(U));
910 return p != nullptr ? new (p) U : nullptr;
911 }
912
913 template <typename U, typename A1>
914 static inline U *create(A1 &&a1) {
915 auto p = (Traits::malloc)(sizeof(U));
916 return p != nullptr ? new (p) U(std::forward<A1>(a1)) : nullptr;
917 }
918
919 template <typename U>
920 static inline void destroy(U *p) {
921 if (p != nullptr) {
922 p->~U();
923 }
924 (Traits::free)(p);
925 }
926
927 private:
928 ConcurrentQueue inner;
929 std::unique_ptr<LightweightSemaphore, void (*)(LightweightSemaphore *)> sema;
930 };
931
932 template <typename T, typename Traits>
933 inline void swap(BlockingConcurrentQueue<T, Traits> &a,
934 BlockingConcurrentQueue<T, Traits> &b) MOODYCAMEL_NOEXCEPT {
935 a.swap(b);
936 }
937
938 } // end namespace moodycamel
939 } // namespace dmlc
940
941 #endif // DMLC_BLOCKINGCONCURRENTQUEUE_H_
942 //! \endcond Doxygen_Suppress