问题描述
C++0x 真的会没有信号量吗?Stack Overflow 上已经有一些关于信号量使用的问题.我一直使用它们(posix 信号量)让一个线程等待另一个线程中的某个事件:
Is it true that C++0x will come without semaphores? There are already some questions on Stack Overflow regarding the use of semaphores. I use them (posix semaphores) all the time to let a thread wait for some event in another thread:
void thread0(...)
{
doSomething0();
event1.wait();
...
}
void thread1(...)
{
doSomething1();
event1.post();
...
}
如果我用互斥锁来做到这一点:
If I would do that with a mutex:
void thread0(...)
{
doSomething0();
event1.lock(); event1.unlock();
...
}
void thread1(...)
{
event1.lock();
doSomethingth1();
event1.unlock();
...
}
问题:很丑,不能保证线程1先锁定互斥体(假设同一个线程应该锁定和解锁互斥体,你也不能在线程0和线程1启动之前锁定事件1).
Problem: It's ugly and it's not guaranteed that thread1 locks the mutex first (Given that the same thread should lock and unlock a mutex, you also can't lock event1 before thread0 and thread1 started).
既然 boost 也没有信号量,那么实现上述目标的最简单方法是什么?
So since boost doesn't have semaphores either, what is the simplest way to achieve the above?
推荐答案
您可以轻松地从互斥锁和条件变量构建一个:
You can easily build one from a mutex and a condition variable:
#include <mutex>
#include <condition_variable>
class semaphore {
std::mutex mutex_;
std::condition_variable condition_;
unsigned long count_ = 0; // Initialized as locked.
public:
void release() {
std::lock_guard<decltype(mutex_)> lock(mutex_);
++count_;
condition_.notify_one();
}
void acquire() {
std::unique_lock<decltype(mutex_)> lock(mutex_);
while(!count_) // Handle spurious wake-ups.
condition_.wait(lock);
--count_;
}
bool try_acquire() {
std::lock_guard<decltype(mutex_)> lock(mutex_);
if(count_) {
--count_;
return true;
}
return false;
}
};
这篇关于C++0x 没有信号量?如何同步线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!