condition_variable.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. //===-------------------- condition_variable.cpp --------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is dual licensed under the MIT and the University of Illinois Open
  6. // Source Licenses. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "__config"
  10. #ifndef _LIBCPP_HAS_NO_THREADS
  11. #include "condition_variable"
  12. #include "thread"
  13. #include "system_error"
  14. #include "cassert"
  15. _LIBCPP_BEGIN_NAMESPACE_STD
  16. condition_variable::~condition_variable()
  17. {
  18. __libcpp_condvar_destroy(&__cv_);
  19. }
  20. void
  21. condition_variable::notify_one() _NOEXCEPT
  22. {
  23. __libcpp_condvar_signal(&__cv_);
  24. }
  25. void
  26. condition_variable::notify_all() _NOEXCEPT
  27. {
  28. __libcpp_condvar_broadcast(&__cv_);
  29. }
  30. void
  31. condition_variable::wait(unique_lock<mutex>& lk) _NOEXCEPT
  32. {
  33. if (!lk.owns_lock())
  34. __throw_system_error(EPERM,
  35. "condition_variable::wait: mutex not locked");
  36. int ec = __libcpp_condvar_wait(&__cv_, lk.mutex()->native_handle());
  37. if (ec)
  38. __throw_system_error(ec, "condition_variable wait failed");
  39. }
  40. void
  41. condition_variable::__do_timed_wait(unique_lock<mutex>& lk,
  42. chrono::time_point<chrono::system_clock, chrono::nanoseconds> tp) _NOEXCEPT
  43. {
  44. using namespace chrono;
  45. if (!lk.owns_lock())
  46. __throw_system_error(EPERM,
  47. "condition_variable::timed wait: mutex not locked");
  48. nanoseconds d = tp.time_since_epoch();
  49. if (d > nanoseconds(0x59682F000000E941))
  50. d = nanoseconds(0x59682F000000E941);
  51. timespec ts;
  52. seconds s = duration_cast<seconds>(d);
  53. typedef decltype(ts.tv_sec) ts_sec;
  54. _LIBCPP_CONSTEXPR ts_sec ts_sec_max = numeric_limits<ts_sec>::max();
  55. if (s.count() < ts_sec_max)
  56. {
  57. ts.tv_sec = static_cast<ts_sec>(s.count());
  58. ts.tv_nsec = static_cast<decltype(ts.tv_nsec)>((d - s).count());
  59. }
  60. else
  61. {
  62. ts.tv_sec = ts_sec_max;
  63. ts.tv_nsec = giga::num - 1;
  64. }
  65. int ec = __libcpp_condvar_timedwait(&__cv_, lk.mutex()->native_handle(), &ts);
  66. if (ec != 0 && ec != ETIMEDOUT)
  67. __throw_system_error(ec, "condition_variable timed_wait failed");
  68. }
  69. void
  70. notify_all_at_thread_exit(condition_variable& cond, unique_lock<mutex> lk)
  71. {
  72. __thread_local_data()->notify_all_at_thread_exit(&cond, lk.release());
  73. }
  74. _LIBCPP_END_NAMESPACE_STD
  75. #endif // !_LIBCPP_HAS_NO_THREADS