条件变量实现安全队列 一些源码的解释
1 2 #include <condition_variable> std::codition_variable cv;
// wake up one waiter
1 void notify_one () noexcept
// wake up all waiters
1 void notify_all() noexcept
Nothing to do to comply with LWG-2135 because std::mutex lock/unlock are nothrow
1 void wait (unique_lock<mutex>& _Lck)
// wait for signal and test predicate
1 2 3 4 5 6 template <class _Predicate >void wait (unique_lock<mutex>& _Lck, _Predicate _Pred) { while (!_Pred()) { wait (_Lck); } }
// wait for duration // TRANSITION, ABI: The standard says that we should use a steady clock, // but unfortunately our ABI speaks struct xtime, which is relative to the system clock.
1 cv_status wait_for (unique_lock<mutex>& _Lck, const chrono::duration<_Rep, _Period>& _Rel_time)
安全队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 template <T>class safe_queue {privare: std::mutex mtx; std::condition_variable cv; std::queue<T> q; public : void push (T value) { std::lock_guard<std::mutex> lk (mtx) ; q.push (value); cv.notify_one (); } void pop () { std::unique_lock<std::mutex> lk (mtx) ; cv.wait (lc, [this ]{return !q.empty ();}) q.pop (); } };
条件变量实现信号量 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Semaphore {privare: int res_; std::mutex mtx_; std::condition_variable cv_; public : Semaphore (int res=0 ) : res_ (res){} ~Semaphore ()=deafult; void wait () { std::unique_lock<std::mutex> lokc (mtx_) ; cv.wait (lock,[&]()->bool {return res_>0 ;}) --res_; } void post () { std::unique_lock<std::mutex> lock (mtx_) ; ++res_; cv.notify_all (); } };