C++ 实现一个信号量

C++ 实现一个信号量

信号量有不少应用场景,事实上只要是生产者-消费者模型,通常都须要一个信号量来控制。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;
};
相关文章
相关标签/搜索