Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mingw.condition_variable.h 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /**
  2. * @file condition_variable.h
  3. * @brief std::condition_variable implementation for MinGW
  4. *
  5. * (c) 2013-2016 by Mega Limited, Auckland, New Zealand
  6. * @author Alexander Vassilev
  7. *
  8. * @copyright Simplified (2-clause) BSD License.
  9. * You should have received a copy of the license along with this
  10. * program.
  11. *
  12. * This code is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  15. * @note
  16. * This file may become part of the mingw-w64 runtime package. If/when this happens,
  17. * the appropriate license will be added, i.e. this code will become dual-licensed,
  18. * and the current BSD 2-clause license will stay.
  19. */
  20. #ifndef MINGW_CONDITIONAL_VARIABLE_H
  21. #define MINGW_CONDITIONAL_VARIABLE_H
  22. #if !defined(__cplusplus) || (__cplusplus < 201103L)
  23. #error A C++11 compiler is required!
  24. #endif
  25. // Use the standard classes for std::, if available.
  26. #include <condition_variable>
  27. #include <cassert>
  28. #include <chrono>
  29. #include <system_error>
  30. #include <sdkddkver.h> // Detect Windows version.
  31. #if (WINVER < _WIN32_WINNT_VISTA)
  32. #include <atomic>
  33. #include <windef.h>
  34. #include <winbase.h> // For CreateSemaphore
  35. #include <handleapi.h>
  36. #endif
  37. #include <synchapi.h>
  38. #include "mingw.mutex.h"
  39. #include "mingw.shared_mutex.h"
  40. #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0501)
  41. #error To use the MinGW-std-threads library, you will need to define the macro _WIN32_WINNT to be 0x0501 (Windows XP) or higher.
  42. #endif
  43. namespace mingw_stdthread
  44. {
  45. #if defined(__MINGW32__ ) && !defined(_GLIBCXX_HAS_GTHREADS)
  46. enum class cv_status { no_timeout, timeout };
  47. #else
  48. using std::cv_status;
  49. #endif
  50. namespace xp
  51. {
  52. // Include the XP-compatible condition_variable classes only if actually
  53. // compiling for XP. The XP-compatible classes are slower than the newer
  54. // versions, and depend on features not compatible with Windows Phone 8.
  55. #if (WINVER < _WIN32_WINNT_VISTA)
  56. class condition_variable_any
  57. {
  58. recursive_mutex mMutex {};
  59. std::atomic<int> mNumWaiters {0};
  60. HANDLE mSemaphore;
  61. HANDLE mWakeEvent {};
  62. public:
  63. using native_handle_type = HANDLE;
  64. native_handle_type native_handle()
  65. {
  66. return mSemaphore;
  67. }
  68. condition_variable_any(const condition_variable_any&) = delete;
  69. condition_variable_any& operator=(const condition_variable_any&) = delete;
  70. condition_variable_any()
  71. : mSemaphore(CreateSemaphoreA(NULL, 0, 0xFFFF, NULL))
  72. {
  73. if (mSemaphore == NULL)
  74. throw std::system_error(GetLastError(), std::generic_category());
  75. mWakeEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
  76. if (mWakeEvent == NULL)
  77. {
  78. CloseHandle(mSemaphore);
  79. throw std::system_error(GetLastError(), std::generic_category());
  80. }
  81. }
  82. ~condition_variable_any()
  83. {
  84. CloseHandle(mWakeEvent);
  85. CloseHandle(mSemaphore);
  86. }
  87. private:
  88. template <class M>
  89. bool wait_impl(M& lock, DWORD timeout)
  90. {
  91. {
  92. lock_guard<recursive_mutex> guard(mMutex);
  93. mNumWaiters++;
  94. }
  95. lock.unlock();
  96. DWORD ret = WaitForSingleObject(mSemaphore, timeout);
  97. mNumWaiters--;
  98. SetEvent(mWakeEvent);
  99. lock.lock();
  100. if (ret == WAIT_OBJECT_0)
  101. return true;
  102. else if (ret == WAIT_TIMEOUT)
  103. return false;
  104. //2 possible cases:
  105. //1)The point in notify_all() where we determine the count to
  106. //increment the semaphore with has not been reached yet:
  107. //we just need to decrement mNumWaiters, but setting the event does not hurt
  108. //
  109. //2)Semaphore has just been released with mNumWaiters just before
  110. //we decremented it. This means that the semaphore count
  111. //after all waiters finish won't be 0 - because not all waiters
  112. //woke up by acquiring the semaphore - we woke up by a timeout.
  113. //The notify_all() must handle this gracefully
  114. //
  115. else
  116. {
  117. using namespace std;
  118. throw system_error(make_error_code((errc)EPROTO));
  119. }
  120. }
  121. public:
  122. template <class M>
  123. void wait(M& lock)
  124. {
  125. wait_impl(lock, INFINITE);
  126. }
  127. template <class M, class Predicate>
  128. void wait(M& lock, Predicate pred)
  129. {
  130. while(!pred())
  131. {
  132. wait(lock);
  133. };
  134. }
  135. void notify_all() noexcept
  136. {
  137. lock_guard<recursive_mutex> lock(mMutex); //block any further wait requests until all current waiters are unblocked
  138. if (mNumWaiters.load() <= 0)
  139. return;
  140. ReleaseSemaphore(mSemaphore, mNumWaiters, NULL);
  141. while(mNumWaiters > 0)
  142. {
  143. auto ret = WaitForSingleObject(mWakeEvent, 1000);
  144. if (ret == WAIT_FAILED || ret == WAIT_ABANDONED)
  145. std::terminate();
  146. }
  147. assert(mNumWaiters == 0);
  148. //in case some of the waiters timed out just after we released the
  149. //semaphore by mNumWaiters, it won't be zero now, because not all waiters
  150. //woke up by acquiring the semaphore. So we must zero the semaphore before
  151. //we accept waiters for the next event
  152. //See _wait_impl for details
  153. while(WaitForSingleObject(mSemaphore, 0) == WAIT_OBJECT_0);
  154. }
  155. void notify_one() noexcept
  156. {
  157. lock_guard<recursive_mutex> lock(mMutex);
  158. int targetWaiters = mNumWaiters.load() - 1;
  159. if (targetWaiters <= -1)
  160. return;
  161. ReleaseSemaphore(mSemaphore, 1, NULL);
  162. while(mNumWaiters > targetWaiters)
  163. {
  164. auto ret = WaitForSingleObject(mWakeEvent, 1000);
  165. if (ret == WAIT_FAILED || ret == WAIT_ABANDONED)
  166. std::terminate();
  167. }
  168. assert(mNumWaiters == targetWaiters);
  169. }
  170. template <class M, class Rep, class Period>
  171. cv_status wait_for(M& lock,
  172. const std::chrono::duration<Rep, Period>& rel_time)
  173. {
  174. using namespace std::chrono;
  175. auto timeout = duration_cast<milliseconds>(rel_time).count();
  176. DWORD waittime = (timeout < INFINITE) ? ((timeout < 0) ? 0 : static_cast<DWORD>(timeout)) : (INFINITE - 1);
  177. bool ret = wait_impl(lock, waittime) || (timeout >= INFINITE);
  178. return ret?cv_status::no_timeout:cv_status::timeout;
  179. }
  180. template <class M, class Rep, class Period, class Predicate>
  181. bool wait_for(M& lock,
  182. const std::chrono::duration<Rep, Period>& rel_time, Predicate pred)
  183. {
  184. return wait_until(lock, std::chrono::steady_clock::now()+rel_time, pred);
  185. }
  186. template <class M, class Clock, class Duration>
  187. cv_status wait_until (M& lock,
  188. const std::chrono::time_point<Clock,Duration>& abs_time)
  189. {
  190. return wait_for(lock, abs_time - Clock::now());
  191. }
  192. template <class M, class Clock, class Duration, class Predicate>
  193. bool wait_until (M& lock,
  194. const std::chrono::time_point<Clock, Duration>& abs_time,
  195. Predicate pred)
  196. {
  197. while (!pred())
  198. {
  199. if (wait_until(lock, abs_time) == cv_status::timeout)
  200. {
  201. return pred();
  202. }
  203. }
  204. return true;
  205. }
  206. };
  207. class condition_variable: condition_variable_any
  208. {
  209. using base = condition_variable_any;
  210. public:
  211. using base::native_handle_type;
  212. using base::native_handle;
  213. using base::base;
  214. using base::notify_all;
  215. using base::notify_one;
  216. void wait(unique_lock<mutex> &lock)
  217. {
  218. base::wait(lock);
  219. }
  220. template <class Predicate>
  221. void wait(unique_lock<mutex>& lock, Predicate pred)
  222. {
  223. base::wait(lock, pred);
  224. }
  225. template <class Rep, class Period>
  226. cv_status wait_for(unique_lock<mutex>& lock, const std::chrono::duration<Rep, Period>& rel_time)
  227. {
  228. return base::wait_for(lock, rel_time);
  229. }
  230. template <class Rep, class Period, class Predicate>
  231. bool wait_for(unique_lock<mutex>& lock, const std::chrono::duration<Rep, Period>& rel_time, Predicate pred)
  232. {
  233. return base::wait_for(lock, rel_time, pred);
  234. }
  235. template <class Clock, class Duration>
  236. cv_status wait_until (unique_lock<mutex>& lock, const std::chrono::time_point<Clock,Duration>& abs_time)
  237. {
  238. return base::wait_until(lock, abs_time);
  239. }
  240. template <class Clock, class Duration, class Predicate>
  241. bool wait_until (unique_lock<mutex>& lock, const std::chrono::time_point<Clock, Duration>& abs_time, Predicate pred)
  242. {
  243. return base::wait_until(lock, abs_time, pred);
  244. }
  245. };
  246. #endif // Compiling for XP
  247. } // Namespace mingw_stdthread::xp
  248. #if (WINVER >= _WIN32_WINNT_VISTA)
  249. namespace vista
  250. {
  251. // If compiling for Vista or higher, use the native condition variable.
  252. class condition_variable
  253. {
  254. static constexpr DWORD kInfinite = 0xffffffffl;
  255. #pragma GCC diagnostic push
  256. #pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
  257. CONDITION_VARIABLE cvariable_ = CONDITION_VARIABLE_INIT;
  258. #pragma GCC diagnostic pop
  259. friend class condition_variable_any;
  260. #if STDMUTEX_RECURSION_CHECKS
  261. template<typename MTX>
  262. inline static void before_wait (MTX * pmutex)
  263. {
  264. pmutex->mOwnerThread.checkSetOwnerBeforeUnlock();
  265. }
  266. template<typename MTX>
  267. inline static void after_wait (MTX * pmutex)
  268. {
  269. pmutex->mOwnerThread.setOwnerAfterLock(GetCurrentThreadId());
  270. }
  271. #else
  272. inline static void before_wait (void *) { }
  273. inline static void after_wait (void *) { }
  274. #endif
  275. bool wait_impl (unique_lock<xp::mutex> & lock, DWORD time)
  276. {
  277. using mutex_handle_type = typename xp::mutex::native_handle_type;
  278. static_assert(std::is_same<mutex_handle_type, PCRITICAL_SECTION>::value,
  279. "Native Win32 condition variable requires std::mutex to \
  280. use native Win32 critical section objects.");
  281. xp::mutex * pmutex = lock.release();
  282. before_wait(pmutex);
  283. BOOL success = SleepConditionVariableCS(&cvariable_,
  284. pmutex->native_handle(),
  285. time);
  286. after_wait(pmutex);
  287. lock = unique_lock<xp::mutex>(*pmutex, adopt_lock);
  288. return success;
  289. }
  290. bool wait_unique (windows7::mutex * pmutex, DWORD time)
  291. {
  292. before_wait(pmutex);
  293. BOOL success = SleepConditionVariableSRW( native_handle(),
  294. pmutex->native_handle(),
  295. time,
  296. // CONDITION_VARIABLE_LOCKMODE_SHARED has a value not specified by
  297. // Microsoft's Dev Center, but is known to be (convertible to) a ULONG. To
  298. // ensure that the value passed to this function is not equal to Microsoft's
  299. // constant, we can either use a static_assert, or simply generate an
  300. // appropriate value.
  301. !CONDITION_VARIABLE_LOCKMODE_SHARED);
  302. after_wait(pmutex);
  303. return success;
  304. }
  305. bool wait_impl (unique_lock<windows7::mutex> & lock, DWORD time)
  306. {
  307. windows7::mutex * pmutex = lock.release();
  308. bool success = wait_unique(pmutex, time);
  309. lock = unique_lock<windows7::mutex>(*pmutex, adopt_lock);
  310. return success;
  311. }
  312. public:
  313. using native_handle_type = PCONDITION_VARIABLE;
  314. native_handle_type native_handle (void)
  315. {
  316. return &cvariable_;
  317. }
  318. condition_variable (void) = default;
  319. ~condition_variable (void) = default;
  320. condition_variable (const condition_variable &) = delete;
  321. condition_variable & operator= (const condition_variable &) = delete;
  322. void notify_one (void) noexcept
  323. {
  324. WakeConditionVariable(&cvariable_);
  325. }
  326. void notify_all (void) noexcept
  327. {
  328. WakeAllConditionVariable(&cvariable_);
  329. }
  330. void wait (unique_lock<mutex> & lock)
  331. {
  332. wait_impl(lock, kInfinite);
  333. }
  334. template<class Predicate>
  335. void wait (unique_lock<mutex> & lock, Predicate pred)
  336. {
  337. while (!pred())
  338. wait(lock);
  339. }
  340. template <class Rep, class Period>
  341. cv_status wait_for(unique_lock<mutex>& lock,
  342. const std::chrono::duration<Rep, Period>& rel_time)
  343. {
  344. using namespace std::chrono;
  345. auto timeout = duration_cast<milliseconds>(rel_time).count();
  346. DWORD waittime = (timeout < kInfinite) ? ((timeout < 0) ? 0 : static_cast<DWORD>(timeout)) : (kInfinite - 1);
  347. bool result = wait_impl(lock, waittime) || (timeout >= kInfinite);
  348. return result ? cv_status::no_timeout : cv_status::timeout;
  349. }
  350. template <class Rep, class Period, class Predicate>
  351. bool wait_for(unique_lock<mutex>& lock,
  352. const std::chrono::duration<Rep, Period>& rel_time,
  353. Predicate pred)
  354. {
  355. return wait_until(lock,
  356. std::chrono::steady_clock::now() + rel_time,
  357. std::move(pred));
  358. }
  359. template <class Clock, class Duration>
  360. cv_status wait_until (unique_lock<mutex>& lock,
  361. const std::chrono::time_point<Clock,Duration>& abs_time)
  362. {
  363. return wait_for(lock, abs_time - Clock::now());
  364. }
  365. template <class Clock, class Duration, class Predicate>
  366. bool wait_until (unique_lock<mutex>& lock,
  367. const std::chrono::time_point<Clock, Duration>& abs_time,
  368. Predicate pred)
  369. {
  370. while (!pred())
  371. {
  372. if (wait_until(lock, abs_time) == cv_status::timeout)
  373. {
  374. return pred();
  375. }
  376. }
  377. return true;
  378. }
  379. };
  380. class condition_variable_any
  381. {
  382. static constexpr DWORD kInfinite = 0xffffffffl;
  383. using native_shared_mutex = windows7::shared_mutex;
  384. condition_variable internal_cv_ {};
  385. // When available, the SRW-based mutexes should be faster than the
  386. // CriticalSection-based mutexes. Only try_lock will be unavailable in Vista,
  387. // and try_lock is not used by condition_variable_any.
  388. windows7::mutex internal_mutex_ {};
  389. template<class L>
  390. bool wait_impl (L & lock, DWORD time)
  391. {
  392. unique_lock<decltype(internal_mutex_)> internal_lock(internal_mutex_);
  393. lock.unlock();
  394. bool success = internal_cv_.wait_impl(internal_lock, time);
  395. lock.lock();
  396. return success;
  397. }
  398. // If the lock happens to be called on a native Windows mutex, skip any extra
  399. // contention.
  400. inline bool wait_impl (unique_lock<mutex> & lock, DWORD time)
  401. {
  402. return internal_cv_.wait_impl(lock, time);
  403. }
  404. // Some shared_mutex functionality is available even in Vista, but it's not
  405. // until Windows 7 that a full implementation is natively possible. The class
  406. // itself is defined, with missing features, at the Vista feature level.
  407. bool wait_impl (unique_lock<native_shared_mutex> & lock, DWORD time)
  408. {
  409. native_shared_mutex * pmutex = lock.release();
  410. bool success = internal_cv_.wait_unique(pmutex, time);
  411. lock = unique_lock<native_shared_mutex>(*pmutex, adopt_lock);
  412. return success;
  413. }
  414. bool wait_impl (shared_lock<native_shared_mutex> & lock, DWORD time)
  415. {
  416. native_shared_mutex * pmutex = lock.release();
  417. BOOL success = SleepConditionVariableSRW(native_handle(),
  418. pmutex->native_handle(), time,
  419. CONDITION_VARIABLE_LOCKMODE_SHARED);
  420. lock = shared_lock<native_shared_mutex>(*pmutex, adopt_lock);
  421. return success;
  422. }
  423. public:
  424. using native_handle_type = typename condition_variable::native_handle_type;
  425. native_handle_type native_handle (void)
  426. {
  427. return internal_cv_.native_handle();
  428. }
  429. void notify_one (void) noexcept
  430. {
  431. internal_cv_.notify_one();
  432. }
  433. void notify_all (void) noexcept
  434. {
  435. internal_cv_.notify_all();
  436. }
  437. condition_variable_any (void) = default;
  438. ~condition_variable_any (void) = default;
  439. template<class L>
  440. void wait (L & lock)
  441. {
  442. wait_impl(lock, kInfinite);
  443. }
  444. template<class L, class Predicate>
  445. void wait (L & lock, Predicate pred)
  446. {
  447. while (!pred())
  448. wait(lock);
  449. }
  450. template <class L, class Rep, class Period>
  451. cv_status wait_for(L& lock, const std::chrono::duration<Rep,Period>& period)
  452. {
  453. using namespace std::chrono;
  454. auto timeout = duration_cast<milliseconds>(period).count();
  455. DWORD waittime = (timeout < kInfinite) ? ((timeout < 0) ? 0 : static_cast<DWORD>(timeout)) : (kInfinite - 1);
  456. bool result = wait_impl(lock, waittime) || (timeout >= kInfinite);
  457. return result ? cv_status::no_timeout : cv_status::timeout;
  458. }
  459. template <class L, class Rep, class Period, class Predicate>
  460. bool wait_for(L& lock, const std::chrono::duration<Rep, Period>& period,
  461. Predicate pred)
  462. {
  463. return wait_until(lock, std::chrono::steady_clock::now() + period,
  464. std::move(pred));
  465. }
  466. template <class L, class Clock, class Duration>
  467. cv_status wait_until (L& lock,
  468. const std::chrono::time_point<Clock,Duration>& abs_time)
  469. {
  470. return wait_for(lock, abs_time - Clock::now());
  471. }
  472. template <class L, class Clock, class Duration, class Predicate>
  473. bool wait_until (L& lock,
  474. const std::chrono::time_point<Clock, Duration>& abs_time,
  475. Predicate pred)
  476. {
  477. while (!pred())
  478. {
  479. if (wait_until(lock, abs_time) == cv_status::timeout)
  480. {
  481. return pred();
  482. }
  483. }
  484. return true;
  485. }
  486. };
  487. } // Namespace vista
  488. #endif
  489. #if WINVER < 0x0600
  490. using xp::condition_variable;
  491. using xp::condition_variable_any;
  492. #else
  493. using vista::condition_variable;
  494. using vista::condition_variable_any;
  495. #endif
  496. } // Namespace mingw_stdthread
  497. // Push objects into std, but only if they are not already there.
  498. namespace std
  499. {
  500. // Because of quirks of the compiler, the common "using namespace std;"
  501. // directive would flatten the namespaces and introduce ambiguity where there
  502. // was none. Direct specification (std::), however, would be unaffected.
  503. // Take the safe option, and include only in the presence of MinGW's win32
  504. // implementation.
  505. #if defined(__MINGW32__ ) && !defined(_GLIBCXX_HAS_GTHREADS)
  506. using mingw_stdthread::cv_status;
  507. using mingw_stdthread::condition_variable;
  508. using mingw_stdthread::condition_variable_any;
  509. #elif !defined(MINGW_STDTHREAD_REDUNDANCY_WARNING) // Skip repetition
  510. #define MINGW_STDTHREAD_REDUNDANCY_WARNING
  511. #pragma message "This version of MinGW seems to include a win32 port of\
  512. pthreads, and probably already has C++11 std threading classes implemented,\
  513. based on pthreads. These classes, found in namespace std, are not overridden\
  514. by the mingw-std-thread library. If you would still like to use this\
  515. implementation (as it is more lightweight), use the classes provided in\
  516. namespace mingw_stdthread."
  517. #endif
  518. }
  519. #endif // MINGW_CONDITIONAL_VARIABLE_H