mingw.condition_variable.h 19 KB

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