atomic_helpers.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. // SPDX-FileCopyrightText: 2013-2016 Cameron Desrochers
  2. // SPDX-FileCopyrightText: 2015 Jeff Preshing
  3. // SPDX-License-Identifier: BSD-2-Clause AND Zlib
  4. // Distributed under the simplified BSD license (see the license file that
  5. // should have come with this header).
  6. // Uses Jeff Preshing's semaphore implementation (under the terms of its
  7. // separate zlib license, embedded below).
  8. #pragma once
  9. // Provides portable (VC++2010+, Intel ICC 13, GCC 4.7+, and anything C++11 compliant)
  10. // implementation of low-level memory barriers, plus a few semi-portable utility macros (for
  11. // inlining and alignment). Also has a basic atomic type (limited to hardware-supported atomics with
  12. // no memory ordering guarantees). Uses the AE_* prefix for macros (historical reasons), and the
  13. // "moodycamel" namespace for symbols.
  14. #include <cassert>
  15. #include <cerrno>
  16. #include <cstdint>
  17. #include <ctime>
  18. #include <type_traits>
  19. // Platform detection
  20. #if defined(__INTEL_COMPILER)
  21. #define AE_ICC
  22. #elif defined(_MSC_VER)
  23. #define AE_VCPP
  24. #elif defined(__GNUC__)
  25. #define AE_GCC
  26. #endif
  27. #if defined(_M_IA64) || defined(__ia64__)
  28. #define AE_ARCH_IA64
  29. #elif defined(_WIN64) || defined(__amd64__) || defined(_M_X64) || defined(__x86_64__)
  30. #define AE_ARCH_X64
  31. #elif defined(_M_IX86) || defined(__i386__)
  32. #define AE_ARCH_X86
  33. #elif defined(_M_PPC) || defined(__powerpc__)
  34. #define AE_ARCH_PPC
  35. #else
  36. #define AE_ARCH_UNKNOWN
  37. #endif
  38. // AE_UNUSED
  39. #define AE_UNUSED(x) ((void)x)
  40. // AE_NO_TSAN/AE_TSAN_ANNOTATE_*
  41. #if defined(__has_feature)
  42. #if __has_feature(thread_sanitizer)
  43. #if __cplusplus >= 201703L // inline variables require C++17
  44. namespace Common {
  45. inline int ae_tsan_global;
  46. }
  47. #define AE_TSAN_ANNOTATE_RELEASE() \
  48. AnnotateHappensBefore(__FILE__, __LINE__, (void*)(&::moodycamel::ae_tsan_global))
  49. #define AE_TSAN_ANNOTATE_ACQUIRE() \
  50. AnnotateHappensAfter(__FILE__, __LINE__, (void*)(&::moodycamel::ae_tsan_global))
  51. extern "C" void AnnotateHappensBefore(const char*, int, void*);
  52. extern "C" void AnnotateHappensAfter(const char*, int, void*);
  53. #else // when we can't work with tsan, attempt to disable its warnings
  54. #define AE_NO_TSAN __attribute__((no_sanitize("thread")))
  55. #endif
  56. #endif
  57. #endif
  58. #ifndef AE_NO_TSAN
  59. #define AE_NO_TSAN
  60. #endif
  61. #ifndef AE_TSAN_ANNOTATE_RELEASE
  62. #define AE_TSAN_ANNOTATE_RELEASE()
  63. #define AE_TSAN_ANNOTATE_ACQUIRE()
  64. #endif
  65. // AE_FORCEINLINE
  66. #if defined(AE_VCPP) || defined(AE_ICC)
  67. #define AE_FORCEINLINE __forceinline
  68. #elif defined(AE_GCC)
  69. //#define AE_FORCEINLINE __attribute__((always_inline))
  70. #define AE_FORCEINLINE inline
  71. #else
  72. #define AE_FORCEINLINE inline
  73. #endif
  74. // AE_ALIGN
  75. #if defined(AE_VCPP) || defined(AE_ICC)
  76. #define AE_ALIGN(x) __declspec(align(x))
  77. #elif defined(AE_GCC)
  78. #define AE_ALIGN(x) __attribute__((aligned(x)))
  79. #else
  80. // Assume GCC compliant syntax...
  81. #define AE_ALIGN(x) __attribute__((aligned(x)))
  82. #endif
  83. // Portable atomic fences implemented below:
  84. namespace Common {
  85. enum memory_order {
  86. memory_order_relaxed,
  87. memory_order_acquire,
  88. memory_order_release,
  89. memory_order_acq_rel,
  90. memory_order_seq_cst,
  91. // memory_order_sync: Forces a full sync:
  92. // #LoadLoad, #LoadStore, #StoreStore, and most significantly, #StoreLoad
  93. memory_order_sync = memory_order_seq_cst
  94. };
  95. } // namespace Common
  96. #if (defined(AE_VCPP) && (_MSC_VER < 1700 || defined(__cplusplus_cli))) || \
  97. (defined(AE_ICC) && __INTEL_COMPILER < 1600)
  98. // VS2010 and ICC13 don't support std::atomic_*_fence, implement our own fences
  99. #include <intrin.h>
  100. #if defined(AE_ARCH_X64) || defined(AE_ARCH_X86)
  101. #define AeFullSync _mm_mfence
  102. #define AeLiteSync _mm_mfence
  103. #elif defined(AE_ARCH_IA64)
  104. #define AeFullSync __mf
  105. #define AeLiteSync __mf
  106. #elif defined(AE_ARCH_PPC)
  107. #include <ppcintrinsics.h>
  108. #define AeFullSync __sync
  109. #define AeLiteSync __lwsync
  110. #endif
  111. #ifdef AE_VCPP
  112. #pragma warning(push)
  113. #pragma warning(disable : 4365) // Disable erroneous 'conversion from long to unsigned int,
  114. // signed/unsigned mismatch' error when using `assert`
  115. #ifdef __cplusplus_cli
  116. #pragma managed(push, off)
  117. #endif
  118. #endif
  119. namespace Common {
  120. AE_FORCEINLINE void compiler_fence(memory_order order) AE_NO_TSAN {
  121. switch (order) {
  122. case memory_order_relaxed:
  123. break;
  124. case memory_order_acquire:
  125. _ReadBarrier();
  126. break;
  127. case memory_order_release:
  128. _WriteBarrier();
  129. break;
  130. case memory_order_acq_rel:
  131. _ReadWriteBarrier();
  132. break;
  133. case memory_order_seq_cst:
  134. _ReadWriteBarrier();
  135. break;
  136. default:
  137. assert(false);
  138. }
  139. }
  140. // x86/x64 have a strong memory model -- all loads and stores have
  141. // acquire and release semantics automatically (so only need compiler
  142. // barriers for those).
  143. #if defined(AE_ARCH_X86) || defined(AE_ARCH_X64)
  144. AE_FORCEINLINE void fence(memory_order order) AE_NO_TSAN {
  145. switch (order) {
  146. case memory_order_relaxed:
  147. break;
  148. case memory_order_acquire:
  149. _ReadBarrier();
  150. break;
  151. case memory_order_release:
  152. _WriteBarrier();
  153. break;
  154. case memory_order_acq_rel:
  155. _ReadWriteBarrier();
  156. break;
  157. case memory_order_seq_cst:
  158. _ReadWriteBarrier();
  159. AeFullSync();
  160. _ReadWriteBarrier();
  161. break;
  162. default:
  163. assert(false);
  164. }
  165. }
  166. #else
  167. AE_FORCEINLINE void fence(memory_order order) AE_NO_TSAN {
  168. // Non-specialized arch, use heavier memory barriers everywhere just in case :-(
  169. switch (order) {
  170. case memory_order_relaxed:
  171. break;
  172. case memory_order_acquire:
  173. _ReadBarrier();
  174. AeLiteSync();
  175. _ReadBarrier();
  176. break;
  177. case memory_order_release:
  178. _WriteBarrier();
  179. AeLiteSync();
  180. _WriteBarrier();
  181. break;
  182. case memory_order_acq_rel:
  183. _ReadWriteBarrier();
  184. AeLiteSync();
  185. _ReadWriteBarrier();
  186. break;
  187. case memory_order_seq_cst:
  188. _ReadWriteBarrier();
  189. AeFullSync();
  190. _ReadWriteBarrier();
  191. break;
  192. default:
  193. assert(false);
  194. }
  195. }
  196. #endif
  197. } // namespace Common
  198. #else
  199. // Use standard library of atomics
  200. #include <atomic>
  201. namespace Common {
  202. AE_FORCEINLINE void compiler_fence(memory_order order) AE_NO_TSAN {
  203. switch (order) {
  204. case memory_order_relaxed:
  205. break;
  206. case memory_order_acquire:
  207. std::atomic_signal_fence(std::memory_order_acquire);
  208. break;
  209. case memory_order_release:
  210. std::atomic_signal_fence(std::memory_order_release);
  211. break;
  212. case memory_order_acq_rel:
  213. std::atomic_signal_fence(std::memory_order_acq_rel);
  214. break;
  215. case memory_order_seq_cst:
  216. std::atomic_signal_fence(std::memory_order_seq_cst);
  217. break;
  218. default:
  219. assert(false);
  220. }
  221. }
  222. AE_FORCEINLINE void fence(memory_order order) AE_NO_TSAN {
  223. switch (order) {
  224. case memory_order_relaxed:
  225. break;
  226. case memory_order_acquire:
  227. AE_TSAN_ANNOTATE_ACQUIRE();
  228. std::atomic_thread_fence(std::memory_order_acquire);
  229. break;
  230. case memory_order_release:
  231. AE_TSAN_ANNOTATE_RELEASE();
  232. std::atomic_thread_fence(std::memory_order_release);
  233. break;
  234. case memory_order_acq_rel:
  235. AE_TSAN_ANNOTATE_ACQUIRE();
  236. AE_TSAN_ANNOTATE_RELEASE();
  237. std::atomic_thread_fence(std::memory_order_acq_rel);
  238. break;
  239. case memory_order_seq_cst:
  240. AE_TSAN_ANNOTATE_ACQUIRE();
  241. AE_TSAN_ANNOTATE_RELEASE();
  242. std::atomic_thread_fence(std::memory_order_seq_cst);
  243. break;
  244. default:
  245. assert(false);
  246. }
  247. }
  248. } // namespace Common
  249. #endif
  250. #if !defined(AE_VCPP) || (_MSC_VER >= 1700 && !defined(__cplusplus_cli))
  251. #define AE_USE_STD_ATOMIC_FOR_WEAK_ATOMIC
  252. #endif
  253. #ifdef AE_USE_STD_ATOMIC_FOR_WEAK_ATOMIC
  254. #include <atomic>
  255. #endif
  256. #include <utility>
  257. // WARNING: *NOT* A REPLACEMENT FOR std::atomic. READ CAREFULLY:
  258. // Provides basic support for atomic variables -- no memory ordering guarantees are provided.
  259. // The guarantee of atomicity is only made for types that already have atomic load and store
  260. // guarantees at the hardware level -- on most platforms this generally means aligned pointers and
  261. // integers (only).
  262. namespace Common {
  263. template <typename T>
  264. class weak_atomic {
  265. public:
  266. AE_NO_TSAN weak_atomic() : value() {}
  267. #ifdef AE_VCPP
  268. #pragma warning(push)
  269. #pragma warning(disable : 4100) // Get rid of (erroneous) 'unreferenced formal parameter' warning
  270. #endif
  271. template <typename U>
  272. AE_NO_TSAN weak_atomic(U&& x) : value(std::forward<U>(x)) {}
  273. #ifdef __cplusplus_cli
  274. // Work around bug with universal reference/nullptr combination that only appears when /clr is
  275. // on
  276. AE_NO_TSAN weak_atomic(nullptr_t) : value(nullptr) {}
  277. #endif
  278. AE_NO_TSAN weak_atomic(weak_atomic const& other) : value(other.load()) {}
  279. AE_NO_TSAN weak_atomic(weak_atomic&& other) : value(std::move(other.load())) {}
  280. #ifdef AE_VCPP
  281. #pragma warning(pop)
  282. #endif
  283. AE_FORCEINLINE operator T() const AE_NO_TSAN {
  284. return load();
  285. }
  286. #ifndef AE_USE_STD_ATOMIC_FOR_WEAK_ATOMIC
  287. template <typename U>
  288. AE_FORCEINLINE weak_atomic const& operator=(U&& x) AE_NO_TSAN {
  289. value = std::forward<U>(x);
  290. return *this;
  291. }
  292. AE_FORCEINLINE weak_atomic const& operator=(weak_atomic const& other) AE_NO_TSAN {
  293. value = other.value;
  294. return *this;
  295. }
  296. AE_FORCEINLINE T load() const AE_NO_TSAN {
  297. return value;
  298. }
  299. AE_FORCEINLINE T fetch_add_acquire(T increment) AE_NO_TSAN {
  300. #if defined(AE_ARCH_X64) || defined(AE_ARCH_X86)
  301. if (sizeof(T) == 4)
  302. return _InterlockedExchangeAdd((long volatile*)&value, (long)increment);
  303. #if defined(_M_AMD64)
  304. else if (sizeof(T) == 8)
  305. return _InterlockedExchangeAdd64((long long volatile*)&value, (long long)increment);
  306. #endif
  307. #else
  308. #error Unsupported platform
  309. #endif
  310. assert(false && "T must be either a 32 or 64 bit type");
  311. return value;
  312. }
  313. AE_FORCEINLINE T fetch_add_release(T increment) AE_NO_TSAN {
  314. #if defined(AE_ARCH_X64) || defined(AE_ARCH_X86)
  315. if (sizeof(T) == 4)
  316. return _InterlockedExchangeAdd((long volatile*)&value, (long)increment);
  317. #if defined(_M_AMD64)
  318. else if (sizeof(T) == 8)
  319. return _InterlockedExchangeAdd64((long long volatile*)&value, (long long)increment);
  320. #endif
  321. #else
  322. #error Unsupported platform
  323. #endif
  324. assert(false && "T must be either a 32 or 64 bit type");
  325. return value;
  326. }
  327. #else
  328. template <typename U>
  329. AE_FORCEINLINE weak_atomic const& operator=(U&& x) AE_NO_TSAN {
  330. value.store(std::forward<U>(x), std::memory_order_relaxed);
  331. return *this;
  332. }
  333. AE_FORCEINLINE weak_atomic const& operator=(weak_atomic const& other) AE_NO_TSAN {
  334. value.store(other.value.load(std::memory_order_relaxed), std::memory_order_relaxed);
  335. return *this;
  336. }
  337. AE_FORCEINLINE T load() const AE_NO_TSAN {
  338. return value.load(std::memory_order_relaxed);
  339. }
  340. AE_FORCEINLINE T fetch_add_acquire(T increment) AE_NO_TSAN {
  341. return value.fetch_add(increment, std::memory_order_acquire);
  342. }
  343. AE_FORCEINLINE T fetch_add_release(T increment) AE_NO_TSAN {
  344. return value.fetch_add(increment, std::memory_order_release);
  345. }
  346. #endif
  347. private:
  348. #ifndef AE_USE_STD_ATOMIC_FOR_WEAK_ATOMIC
  349. // No std::atomic support, but still need to circumvent compiler optimizations.
  350. // `volatile` will make memory access slow, but is guaranteed to be reliable.
  351. volatile T value;
  352. #else
  353. std::atomic<T> value;
  354. #endif
  355. };
  356. } // namespace Common
  357. // Portable single-producer, single-consumer semaphore below:
  358. #if defined(_WIN32)
  359. // Avoid including windows.h in a header; we only need a handful of
  360. // items, so we'll redeclare them here (this is relatively safe since
  361. // the API generally has to remain stable between Windows versions).
  362. // I know this is an ugly hack but it still beats polluting the global
  363. // namespace with thousands of generic names or adding a .cpp for nothing.
  364. extern "C" {
  365. struct _SECURITY_ATTRIBUTES;
  366. __declspec(dllimport) void* __stdcall CreateSemaphoreW(_SECURITY_ATTRIBUTES* lpSemaphoreAttributes,
  367. long lInitialCount, long lMaximumCount,
  368. const wchar_t* lpName);
  369. __declspec(dllimport) int __stdcall CloseHandle(void* hObject);
  370. __declspec(dllimport) unsigned long __stdcall WaitForSingleObject(void* hHandle,
  371. unsigned long dwMilliseconds);
  372. __declspec(dllimport) int __stdcall ReleaseSemaphore(void* hSemaphore, long lReleaseCount,
  373. long* lpPreviousCount);
  374. }
  375. #elif defined(__MACH__)
  376. #include <mach/mach.h>
  377. #elif defined(__unix__)
  378. #include <semaphore.h>
  379. #elif defined(FREERTOS)
  380. #include <FreeRTOS.h>
  381. #include <semphr.h>
  382. #include <task.h>
  383. #endif
  384. namespace Common {
  385. // Code in the spsc_sema namespace below is an adaptation of Jeff Preshing's
  386. // portable + lightweight semaphore implementations, originally from
  387. // https://github.com/preshing/cpp11-on-multicore/blob/master/common/sema.h
  388. // LICENSE:
  389. // Copyright (c) 2015 Jeff Preshing
  390. //
  391. // This software is provided 'as-is', without any express or implied
  392. // warranty. In no event will the authors be held liable for any damages
  393. // arising from the use of this software.
  394. //
  395. // Permission is granted to anyone to use this software for any purpose,
  396. // including commercial applications, and to alter it and redistribute it
  397. // freely, subject to the following restrictions:
  398. //
  399. // 1. The origin of this software must not be misrepresented; you must not
  400. // claim that you wrote the original software. If you use this software
  401. // in a product, an acknowledgement in the product documentation would be
  402. // appreciated but is not required.
  403. // 2. Altered source versions must be plainly marked as such, and must not be
  404. // misrepresented as being the original software.
  405. // 3. This notice may not be removed or altered from any source distribution.
  406. namespace spsc_sema {
  407. #if defined(_WIN32)
  408. class Semaphore {
  409. private:
  410. void* m_hSema;
  411. Semaphore(const Semaphore& other);
  412. Semaphore& operator=(const Semaphore& other);
  413. public:
  414. AE_NO_TSAN Semaphore(int initialCount = 0) : m_hSema() {
  415. assert(initialCount >= 0);
  416. const long maxLong = 0x7fffffff;
  417. m_hSema = CreateSemaphoreW(nullptr, initialCount, maxLong, nullptr);
  418. assert(m_hSema);
  419. }
  420. AE_NO_TSAN ~Semaphore() {
  421. CloseHandle(m_hSema);
  422. }
  423. bool wait() AE_NO_TSAN {
  424. const unsigned long infinite = 0xffffffff;
  425. return WaitForSingleObject(m_hSema, infinite) == 0;
  426. }
  427. bool try_wait() AE_NO_TSAN {
  428. return WaitForSingleObject(m_hSema, 0) == 0;
  429. }
  430. bool timed_wait(std::uint64_t usecs) AE_NO_TSAN {
  431. return WaitForSingleObject(m_hSema, (unsigned long)(usecs / 1000)) == 0;
  432. }
  433. void signal(int count = 1) AE_NO_TSAN {
  434. while (!ReleaseSemaphore(m_hSema, count, nullptr))
  435. ;
  436. }
  437. };
  438. #elif defined(__MACH__)
  439. //---------------------------------------------------------
  440. // Semaphore (Apple iOS and OSX)
  441. // Can't use POSIX semaphores due to
  442. // http://lists.apple.com/archives/darwin-kernel/2009/Apr/msg00010.html
  443. //---------------------------------------------------------
  444. class Semaphore {
  445. private:
  446. semaphore_t m_sema;
  447. Semaphore(const Semaphore& other);
  448. Semaphore& operator=(const Semaphore& other);
  449. public:
  450. AE_NO_TSAN Semaphore(int initialCount = 0) : m_sema() {
  451. assert(initialCount >= 0);
  452. kern_return_t rc =
  453. semaphore_create(mach_task_self(), &m_sema, SYNC_POLICY_FIFO, initialCount);
  454. assert(rc == KERN_SUCCESS);
  455. AE_UNUSED(rc);
  456. }
  457. AE_NO_TSAN ~Semaphore() {
  458. semaphore_destroy(mach_task_self(), m_sema);
  459. }
  460. bool wait() AE_NO_TSAN {
  461. return semaphore_wait(m_sema) == KERN_SUCCESS;
  462. }
  463. bool try_wait() AE_NO_TSAN {
  464. return timed_wait(0);
  465. }
  466. bool timed_wait(std::uint64_t timeout_usecs) AE_NO_TSAN {
  467. mach_timespec_t ts;
  468. ts.tv_sec = static_cast<unsigned int>(timeout_usecs / 1000000);
  469. ts.tv_nsec = static_cast<int>((timeout_usecs % 1000000) * 1000);
  470. // added in OSX 10.10:
  471. // https://developer.apple.com/library/prerelease/mac/documentation/General/Reference/APIDiffsMacOSX10_10SeedDiff/modules/Darwin.html
  472. kern_return_t rc = semaphore_timedwait(m_sema, ts);
  473. return rc == KERN_SUCCESS;
  474. }
  475. void signal() AE_NO_TSAN {
  476. while (semaphore_signal(m_sema) != KERN_SUCCESS)
  477. ;
  478. }
  479. void signal(int count) AE_NO_TSAN {
  480. while (count-- > 0) {
  481. while (semaphore_signal(m_sema) != KERN_SUCCESS)
  482. ;
  483. }
  484. }
  485. };
  486. #elif defined(__unix__)
  487. //---------------------------------------------------------
  488. // Semaphore (POSIX, Linux)
  489. //---------------------------------------------------------
  490. class Semaphore {
  491. private:
  492. sem_t m_sema;
  493. Semaphore(const Semaphore& other);
  494. Semaphore& operator=(const Semaphore& other);
  495. public:
  496. AE_NO_TSAN Semaphore(int initialCount = 0) : m_sema() {
  497. assert(initialCount >= 0);
  498. int rc = sem_init(&m_sema, 0, static_cast<unsigned int>(initialCount));
  499. assert(rc == 0);
  500. AE_UNUSED(rc);
  501. }
  502. AE_NO_TSAN ~Semaphore() {
  503. sem_destroy(&m_sema);
  504. }
  505. bool wait() AE_NO_TSAN {
  506. // http://stackoverflow.com/questions/2013181/gdb-causes-sem-wait-to-fail-with-eintr-error
  507. int rc;
  508. do {
  509. rc = sem_wait(&m_sema);
  510. } while (rc == -1 && errno == EINTR);
  511. return rc == 0;
  512. }
  513. bool try_wait() AE_NO_TSAN {
  514. int rc;
  515. do {
  516. rc = sem_trywait(&m_sema);
  517. } while (rc == -1 && errno == EINTR);
  518. return rc == 0;
  519. }
  520. bool timed_wait(std::uint64_t usecs) AE_NO_TSAN {
  521. struct timespec ts;
  522. const int usecs_in_1_sec = 1000000;
  523. const int nsecs_in_1_sec = 1000000000;
  524. clock_gettime(CLOCK_REALTIME, &ts);
  525. ts.tv_sec += static_cast<time_t>(usecs / usecs_in_1_sec);
  526. ts.tv_nsec += static_cast<long>(usecs % usecs_in_1_sec) * 1000;
  527. // sem_timedwait bombs if you have more than 1e9 in tv_nsec
  528. // so we have to clean things up before passing it in
  529. if (ts.tv_nsec >= nsecs_in_1_sec) {
  530. ts.tv_nsec -= nsecs_in_1_sec;
  531. ++ts.tv_sec;
  532. }
  533. int rc;
  534. do {
  535. rc = sem_timedwait(&m_sema, &ts);
  536. } while (rc == -1 && errno == EINTR);
  537. return rc == 0;
  538. }
  539. void signal() AE_NO_TSAN {
  540. while (sem_post(&m_sema) == -1)
  541. ;
  542. }
  543. void signal(int count) AE_NO_TSAN {
  544. while (count-- > 0) {
  545. while (sem_post(&m_sema) == -1)
  546. ;
  547. }
  548. }
  549. };
  550. #elif defined(FREERTOS)
  551. //---------------------------------------------------------
  552. // Semaphore (FreeRTOS)
  553. //---------------------------------------------------------
  554. class Semaphore {
  555. private:
  556. SemaphoreHandle_t m_sema;
  557. Semaphore(const Semaphore& other);
  558. Semaphore& operator=(const Semaphore& other);
  559. public:
  560. AE_NO_TSAN Semaphore(int initialCount = 0) : m_sema() {
  561. assert(initialCount >= 0);
  562. m_sema = xSemaphoreCreateCounting(static_cast<UBaseType_t>(~0ull),
  563. static_cast<UBaseType_t>(initialCount));
  564. assert(m_sema);
  565. }
  566. AE_NO_TSAN ~Semaphore() {
  567. vSemaphoreDelete(m_sema);
  568. }
  569. bool wait() AE_NO_TSAN {
  570. return xSemaphoreTake(m_sema, portMAX_DELAY) == pdTRUE;
  571. }
  572. bool try_wait() AE_NO_TSAN {
  573. // Note: In an ISR context, if this causes a task to unblock,
  574. // the caller won't know about it
  575. if (xPortIsInsideInterrupt())
  576. return xSemaphoreTakeFromISR(m_sema, NULL) == pdTRUE;
  577. return xSemaphoreTake(m_sema, 0) == pdTRUE;
  578. }
  579. bool timed_wait(std::uint64_t usecs) AE_NO_TSAN {
  580. std::uint64_t msecs = usecs / 1000;
  581. TickType_t ticks = static_cast<TickType_t>(msecs / portTICK_PERIOD_MS);
  582. if (ticks == 0)
  583. return try_wait();
  584. return xSemaphoreTake(m_sema, ticks) == pdTRUE;
  585. }
  586. void signal() AE_NO_TSAN {
  587. // Note: In an ISR context, if this causes a task to unblock,
  588. // the caller won't know about it
  589. BaseType_t rc;
  590. if (xPortIsInsideInterrupt())
  591. rc = xSemaphoreGiveFromISR(m_sema, NULL);
  592. else
  593. rc = xSemaphoreGive(m_sema);
  594. assert(rc == pdTRUE);
  595. AE_UNUSED(rc);
  596. }
  597. void signal(int count) AE_NO_TSAN {
  598. while (count-- > 0)
  599. signal();
  600. }
  601. };
  602. #else
  603. #error Unsupported platform! (No semaphore wrapper available)
  604. #endif
  605. //---------------------------------------------------------
  606. // LightweightSemaphore
  607. //---------------------------------------------------------
  608. class LightweightSemaphore {
  609. public:
  610. typedef std::make_signed<std::size_t>::type ssize_t;
  611. private:
  612. weak_atomic<ssize_t> m_count;
  613. Semaphore m_sema;
  614. bool waitWithPartialSpinning(std::int64_t timeout_usecs = -1) AE_NO_TSAN {
  615. ssize_t oldCount;
  616. // Is there a better way to set the initial spin count?
  617. // If we lower it to 1000, testBenaphore becomes 15x slower on my Core i7-5930K Windows PC,
  618. // as threads start hitting the kernel semaphore.
  619. int spin = 1024;
  620. while (--spin >= 0) {
  621. if (m_count.load() > 0) {
  622. m_count.fetch_add_acquire(-1);
  623. return true;
  624. }
  625. compiler_fence(memory_order_acquire); // Prevent the compiler from collapsing the loop.
  626. }
  627. oldCount = m_count.fetch_add_acquire(-1);
  628. if (oldCount > 0)
  629. return true;
  630. if (timeout_usecs < 0) {
  631. if (m_sema.wait())
  632. return true;
  633. }
  634. if (timeout_usecs > 0 && m_sema.timed_wait(static_cast<uint64_t>(timeout_usecs)))
  635. return true;
  636. // At this point, we've timed out waiting for the semaphore, but the
  637. // count is still decremented indicating we may still be waiting on
  638. // it. So we have to re-adjust the count, but only if the semaphore
  639. // wasn't signaled enough times for us too since then. If it was, we
  640. // need to release the semaphore too.
  641. while (true) {
  642. oldCount = m_count.fetch_add_release(1);
  643. if (oldCount < 0)
  644. return false; // successfully restored things to the way they were
  645. // Oh, the producer thread just signaled the semaphore after all. Try again:
  646. oldCount = m_count.fetch_add_acquire(-1);
  647. if (oldCount > 0 && m_sema.try_wait())
  648. return true;
  649. }
  650. }
  651. public:
  652. AE_NO_TSAN LightweightSemaphore(ssize_t initialCount = 0) : m_count(initialCount), m_sema() {
  653. assert(initialCount >= 0);
  654. }
  655. bool tryWait() AE_NO_TSAN {
  656. if (m_count.load() > 0) {
  657. m_count.fetch_add_acquire(-1);
  658. return true;
  659. }
  660. return false;
  661. }
  662. bool wait() AE_NO_TSAN {
  663. return tryWait() || waitWithPartialSpinning();
  664. }
  665. bool wait(std::int64_t timeout_usecs) AE_NO_TSAN {
  666. return tryWait() || waitWithPartialSpinning(timeout_usecs);
  667. }
  668. void signal(ssize_t count = 1) AE_NO_TSAN {
  669. assert(count >= 0);
  670. ssize_t oldCount = m_count.fetch_add_release(count);
  671. assert(oldCount >= -1);
  672. if (oldCount < 0) {
  673. m_sema.signal(1);
  674. }
  675. }
  676. std::size_t availableApprox() const AE_NO_TSAN {
  677. ssize_t count = m_count.load();
  678. return count > 0 ? static_cast<std::size_t>(count) : 0;
  679. }
  680. };
  681. } // namespace spsc_sema
  682. } // namespace Common
  683. #if defined(AE_VCPP) && (_MSC_VER < 1700 || defined(__cplusplus_cli))
  684. #pragma warning(pop)
  685. #ifdef __cplusplus_cli
  686. #pragma managed(pop)
  687. #endif
  688. #endif