如何使用以下信号量代码
How to use the following Semaphore code
我正在读关于Semaphores的文章。据我所知,信号量只允许一定数量的线程访问特定的资源。我看到了这篇文章,它解释了如何使用条件变量和互斥体创建一个简单的信号量类。易于访问的代码是从链接粘贴到这里的
#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习语作为信号量:
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()
将在退出函数之前被调用,同样在抛出异常且堆栈展开未终止的情况下也是如此。
一个更好的解决方案是将Semaphore的方法:wait
重命名为lock
,notify
重命名为unlock
。在这种情况下,可以使用std::lock_guard<Semaphore>
来代替自写的SemaphoreLock
类。
相关文章:
- 删除旧的信号量系统V
- 父进程和子进程之间的 POSIX 信号量
- 访问共享内存而不使用易失性、std::atomic、信号量、互斥锁和自旋锁
- 多线程.如果我使用信号量,我可以在开始时创建很多线程还是应该只有几个线程?
- C/C++ - 用于按顺序打印数字的 sem_t 类型的单个信号量
- 单车道桥 使用信号量进行同步
- 用于 64 位/32 位 IPC 的 POSIX 信号量的替代方案?
- 这个餐饮哲学家问题(dpp)的解决方案是如何工作的?互斥体和信号量
- 发布信号量返回错误 6(无效句柄)
- 在 C Linux 中使用三个线程使用信号量同步按顺序打印 3 4 5 50 次
- 在使用 pthread 和信号量实现生产者-消费者问题时需要帮助
- 如何让一个线程继续,而另一个线程正在等待C++中的信号量
- 实现信号量
- 计算信号量还是互斥体?
- POSIX 信号量在高争用/负载下不起作用
- C++:提升:托管共享内存是否需要信号量锁
- 信号量的问题
- 如何使用Windows API直接将进程"assign"到信号量?
- 从主线程C++更新信号量
- 如何使用以下信号量代码