编程语言
首页 > 编程语言> > C++实现信号量

C++实现信号量

作者:互联网

背景
实现
代码toc

背景

信号量与条件变量差异对比

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;
}


来自为知笔记(Wiz)

标签:实现,阻塞,C++,信号量,线程,Semaphore,iCount,wait
来源: https://www.cnblogs.com/Keeping-Fit/p/14979384.html