|
| 1 | +#pragma once |
| 2 | + |
| 3 | +#ifdef __APPLE__ |
| 4 | +#include <TargetConditionals.h> |
| 5 | +#include <version> |
| 6 | +#endif |
| 7 | + |
| 8 | +/* |
| 9 | + a simple semaphore interface. |
| 10 | +
|
| 11 | + if >= C++20 and , |
| 12 | + use std::counting_semaphore otherwise, |
| 13 | + use moodycamel::LightweightSemaphore |
| 14 | +*/ |
| 15 | + |
| 16 | +#if __has_include(<semaphore>) && defined(__cpp_lib_semaphore) && __cpp_lib_semaphore >= 201907L |
| 17 | +#define C10_SEMAPHORE_USE_STL |
| 18 | +#endif |
| 19 | + |
| 20 | +#ifdef C10_SEMAPHORE_USE_STL |
| 21 | +#include <semaphore> |
| 22 | +#else |
| 23 | +// To use moodycamel semaphore, we need to include the header file |
| 24 | +// for concurrentqueue first. Hiding implementation detail here. |
| 25 | +#ifdef BLOCK_SIZE |
| 26 | +#pragma push_macro("BLOCK_SIZE") |
| 27 | +#undef BLOCK_SIZE |
| 28 | +#include <moodycamel/concurrentqueue.h> // @manual |
| 29 | +#pragma pop_macro("BLOCK_SIZE") |
| 30 | +#else |
| 31 | +#include <moodycamel/concurrentqueue.h> // @manual |
| 32 | +#endif |
| 33 | + |
| 34 | +#include <moodycamel/lightweightsemaphore.h> // @manual |
| 35 | +#endif |
| 36 | + |
| 37 | +namespace c10 { |
| 38 | + |
| 39 | +class Semaphore { |
| 40 | + public: |
| 41 | + Semaphore(int32_t initial_count = 0) : impl_(initial_count) {} |
| 42 | + |
| 43 | + void release(int32_t n = 1) { |
| 44 | +#ifdef C10_SEMAPHORE_USE_STL |
| 45 | + impl_.release(n); |
| 46 | +#else |
| 47 | + impl_.signal(n); |
| 48 | +#endif |
| 49 | + } |
| 50 | + |
| 51 | + void acquire() { |
| 52 | +#ifdef C10_SEMAPHORE_USE_STL |
| 53 | + impl_.acquire(); |
| 54 | +#else |
| 55 | + impl_.wait(); |
| 56 | +#endif |
| 57 | + } |
| 58 | + |
| 59 | + bool tryAcquire() { |
| 60 | +#ifdef C10_SEMAPHORE_USE_STL |
| 61 | + return impl_.try_acquire(); |
| 62 | +#else |
| 63 | + return impl_.tryWait(); |
| 64 | +#endif |
| 65 | + } |
| 66 | + |
| 67 | + private: |
| 68 | +#ifdef C10_SEMAPHORE_USE_STL |
| 69 | + std::counting_semaphore<> impl_; |
| 70 | +#else |
| 71 | + moodycamel::LightweightSemaphore impl_; |
| 72 | +#endif |
| 73 | +}; |
| 74 | +} // namespace c10 |
| 75 | + |
| 76 | +#undef C10_SEMAPHORE_USE_STL |
0 commit comments