condition_variable.cpp revision 227983
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 10#include "condition_variable" 11#include "thread" 12#include "system_error" 13#include "cassert" 14 15_LIBCPP_BEGIN_NAMESPACE_STD 16 17condition_variable::~condition_variable() 18{ 19 int e = pthread_cond_destroy(&__cv_); 20// assert(e == 0); 21} 22 23void 24condition_variable::notify_one() 25{ 26 pthread_cond_signal(&__cv_); 27} 28 29void 30condition_variable::notify_all() 31{ 32 pthread_cond_broadcast(&__cv_); 33} 34 35void 36condition_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 46void 47condition_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 64void 65notify_all_at_thread_exit(condition_variable& cond, unique_lock<mutex> lk) 66{ 67 __thread_local_data()->notify_all_at_thread_exit(&cond, lk.release()); 68} 69 70_LIBCPP_END_NAMESPACE_STD 71