atomic_helpers.h 24 KB

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