信號量有不少應用場景,事實上只要是生產者-消費者模型,通常都須要一個信號量來控制。oop
POSIX接口是有PV信號量API的。但C++標準沒有。下面是一個PV信號量的簡單實現。有些不熟悉條件變量的人或許產生下面的疑問:
一、wait裏已經對mtx加鎖並阻塞了,notify那裏申請mtx的行爲豈不是一直等待?
條件變量的實現,會自動解鎖mutex並阻塞當前線程。參見 std::condition_variable
二、爲何要在一個while循環裏wait條件變量?
簡而言之,就是操做系統不能保證每次線程被喚醒時,條件變量的條件都是知足的;但能夠保證,只要條件知足,就必定會喚醒。
參見Spurious wakeupthis
#include <mutex> #include <condition_variable> class semaphore { public: semaphore(int count_ = 0) : count(count_) {} inline void notify() { std::unique_lock<std::mutex> lock(mtx); count++; cv.notify_one(); } inline void wait() { std::unique_lock<std::mutex> lock(mtx); while (count == 0) { cv.wait(lock); } //The while loop can be replaced as below. //cv.wait ( lock, [&] () { return this->count > 0; } ); count--; } private: std::mutex mtx; std::condition_variable cv; int count; };