Howard Hinnant | bc8d3f9 | 2010-05-11 19:42:16 +0000 | [diff] [blame] | 1 | //===-------------------- condition_variable.cpp --------------------------===// |
| 2 | // |
Howard Hinnant | f5256e1 | 2010-05-11 21:36:01 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
Howard Hinnant | bc8d3f9 | 2010-05-11 19:42:16 +0000 | [diff] [blame] | 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | |
| 10 | #include "condition_variable" |
| 11 | #include "thread" |
| 12 | #include "system_error" |
| 13 | #include "cassert" |
| 14 | |
| 15 | _LIBCPP_BEGIN_NAMESPACE_STD |
| 16 | |
| 17 | condition_variable::~condition_variable() |
| 18 | { |
| 19 | int e = pthread_cond_destroy(&__cv_); |
| 20 | // assert(e == 0); |
| 21 | } |
| 22 | |
| 23 | void |
| 24 | condition_variable::notify_one() |
| 25 | { |
| 26 | pthread_cond_signal(&__cv_); |
| 27 | } |
| 28 | |
| 29 | void |
| 30 | condition_variable::notify_all() |
| 31 | { |
| 32 | pthread_cond_broadcast(&__cv_); |
| 33 | } |
| 34 | |
| 35 | void |
| 36 | condition_variable::wait(unique_lock<mutex>& lk) |
| 37 | { |
| 38 | if (!lk.owns_lock()) |
| 39 | __throw_system_error(EPERM, |
| 40 | "condition_variable::wait: mutex not locked"); |
| 41 | int ec = pthread_cond_wait(&__cv_, lk.mutex()->native_handle()); |
| 42 | if (ec) |
| 43 | __throw_system_error(ec, "condition_variable wait failed"); |
| 44 | } |
| 45 | |
| 46 | void |
| 47 | condition_variable::__do_timed_wait(unique_lock<mutex>& lk, |
| 48 | chrono::time_point<chrono::system_clock, chrono::nanoseconds> tp) |
| 49 | { |
| 50 | using namespace chrono; |
| 51 | if (!lk.owns_lock()) |
| 52 | __throw_system_error(EPERM, |
| 53 | "condition_variable::timed wait: mutex not locked"); |
| 54 | nanoseconds d = tp.time_since_epoch(); |
| 55 | timespec ts; |
| 56 | seconds s = duration_cast<seconds>(d); |
| 57 | ts.tv_sec = static_cast<decltype(ts.tv_sec)>(s.count()); |
| 58 | ts.tv_nsec = static_cast<decltype(ts.tv_nsec)>((d - s).count()); |
| 59 | int ec = pthread_cond_timedwait(&__cv_, lk.mutex()->native_handle(), &ts); |
| 60 | if (ec != 0 && ec != ETIMEDOUT) |
| 61 | __throw_system_error(ec, "condition_variable timed_wait failed"); |
| 62 | } |
| 63 | |
| 64 | _LIBCPP_END_NAMESPACE_STD |