conditional variable模拟信号量

C++ May 30, 2020

属于基本操作

#include <condition_variable>
#include <mutex>
class Semaphore {
public:
    Semaphore(int count = 0) : count(count) {

    }

    void signal() {
        std::unique_lock<std::mutex> lock(this->mx);
        count++;
        this->cv.notify_all();
    }

    void wait() {
        std::unique_lock<std::mutex> lock(this->mx);
        this->cv.wait(lock, [this](){
            return this->count > 0;
        });
        count--;
    }

private:
    std::condition_variable cv;
    std::mutex mx;
    int count;
};
Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.