// // Created by YY on 2022/12/30. // #ifndef MYAPPLICATION3_SEMAPHORE_H #define MYAPPLICATION3_SEMAPHORE_H #include #include namespace ilovers{ class semaphore { public: semaphore(int value=1): count{value}, wakeups{0} {} void wait(void) { std::unique_lock lock{mutex}; if (--count<0) { // count is not enough ? condition.wait(lock, [&]()->bool{ return wakeups>0;}); // suspend and wait ... --wakeups; // ok, me wakeup ! } } void signal(void) { std::lock_guard lock{mutex}; if(++count<=0) { // have some thread suspended ? ++wakeups; condition.notify_one(); // notify one ! } } private: int count; int wakeups; std::mutex mutex; std::condition_variable condition; }; }; #endif //MYAPPLICATION3_SEMAPHORE_H