c++ - 如何使用以下信号量代码

标签 c++ multithreading semaphore

我正在阅读有关信号量的内容。据我了解,信号量只允许一定数量的线程访问特定资源。我遇到了这个 post它解释了如何使用条件变量和互斥锁创建一个简单的信号量类。方便访问的代码从该链接粘贴到此处

#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);
        }
        count--;
    }

private:
    std::mutex mtx;
    std::condition_variable cv;
    int count;
};

我的问题是如何使用上面的类来使这个方法一次只能被 3 个线程访问

void SomeFunction
{
  ------------------------------> Only 3 threads should be allowed access to this function concurrently
  int a = getSomeValue();
  //Do something useful
  ------------------------------>
}

我想我会做这样的事情

   Semaphore s(3);
   void SomeFunction
    {
        s.wait();
        int a = getSomeValue();
       //Do sometning useful
        s.notify();
    }

但是我不确定何时会调用 wait()notify()

最佳答案

最好用RAII idiom对于信号量:

class SemaphoreLock
{
public:
    SemaphoreLock(Semaphore& s)
        : _pS(&s)
    {
        _pS->wait();
    }
    ~SemaphoreLock()
    {
        _pS->notify();
    }
private:
    Semaphore* _pS;
};

Semaphore s(3);
void SomeFunction()
{
    SemaphoreLock sl(s);
    // implement the function here
}

如果SemaphoreLock对象在函数体的最开始声明,然后是wait()将在进入函数时被调用,notify()将在退出函数之前调用,如果抛出异常且堆栈展开未终止,也是如此。

更好的解决方案可能是重命名信号量的方法:wait进入locknotify进入unlock .在这种情况下,可以使用 std::lock_guard<Semaphore>代替自写SemaphoreLock类。

关于c++ - 如何使用以下信号量代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31190252/

相关文章:

c - 实现 FCFS 调度程序

java - 新线程和调用线程都会被阻塞 Java Semaphore

c++ - 错误 : expression cannot be used as function - operator()

c++ - 适配器模式 : support underlying data that can be const or non-const, 优雅

c++ - 如何让 tr1::array 分配对齐内存?

java - 安卓 : Wait for a background task to finish in main thread

java - 语句执行与同步方法执行交错

c++ - qt中的动态成员分配

multithreading - C++ std::mutex和Windows CreateMutex有什么区别

concurrency - 寻找监视器与信号量的良好类比/示例