信号量与条件变量差异对比
C++标准库仅有条件变量,而没有信号量,下面实现一个跨平台信号量
信号量最基本的操作有三个
#pragma once #include <mutex> #include <condition_variable> class Semaphore final{ public: explicit Semaphore(int iCount = 0); ~Semaphore(); void Signal(); void Wait(); int GetValue(); Semaphore(const Semaphore& rhs) = delete; Semaphore(Semaphore&& rhs) = delete; Semaphore& operator=(const Semaphore& rhs) = delete; Semaphore& operator=(Semaphore&& rhs) = delete; private: std::mutex m_mLock; std::condition_variable m_cConditionVariable; int m_iCount; };
#include "Semaphore.h" Semaphore::Semaphore(int iCount) : m_iCount(iCount){ } Semaphore::~Semaphore(){ } void Semaphore::Signal(){ std::unique_lock<std::mutex> lock(m_mLock); if(++m_iCount >= 0){ m_cConditionVariable.notify_one(); } } void Semaphore::Wait(){ std::unique_lock<std::mutex> lock(m_mLock); --m_iCount; m_cConditionVariable.wait(lock, [this] { return m_iCount >= 0; }); } int Semaphore::GetValue(){ std::unique_lock<std::mutex> lock(m_mLock); return m_iCount; }