7
我明白我已經問過這個問題之前:What is the C++ equivalent for AutoResetEvent under Linux?有沒有一種簡單的方法在C++ 0x中實現AutoResetEvent?
不過,我正在學習,在C++ 0x中,線程庫是由簡單得多,所以我想出去再提出這個問題,是有在C++ 0x中實現AutoResetEvent的簡單方法?
我明白我已經問過這個問題之前:What is the C++ equivalent for AutoResetEvent under Linux?有沒有一種簡單的方法在C++ 0x中實現AutoResetEvent?
不過,我正在學習,在C++ 0x中,線程庫是由簡單得多,所以我想出去再提出這個問題,是有在C++ 0x中實現AutoResetEvent的簡單方法?
這裏是accepted answer to your first question的翻譯使用C++ 11點的工具:
#include <mutex>
#include <condition_variable>
#include <thread>
#include <stdio.h>
class AutoResetEvent
{
public:
explicit AutoResetEvent(bool initial = false);
void Set();
void Reset();
bool WaitOne();
private:
AutoResetEvent(const AutoResetEvent&);
AutoResetEvent& operator=(const AutoResetEvent&); // non-copyable
bool flag_;
std::mutex protect_;
std::condition_variable signal_;
};
AutoResetEvent::AutoResetEvent(bool initial)
: flag_(initial)
{
}
void AutoResetEvent::Set()
{
std::lock_guard<std::mutex> _(protect_);
flag_ = true;
signal_.notify_one();
}
void AutoResetEvent::Reset()
{
std::lock_guard<std::mutex> _(protect_);
flag_ = false;
}
bool AutoResetEvent::WaitOne()
{
std::unique_lock<std::mutex> lk(protect_);
while(!flag_) // prevent spurious wakeups from doing harm
signal_.wait(lk);
flag_ = false; // waiting resets the flag
return true;
}
AutoResetEvent event;
void otherthread()
{
event.WaitOne();
printf("Hello from other thread!\n");
}
int main()
{
std::thread h(otherthread);
printf("Hello from the first thread\n");
event.Set();
h.join();
}
輸出:
Hello from the first thread
Hello from other thread!
更新
在下面tobsen指出,AutoResetEvent
評論具有signal_.notify_all()
而不是的語義。我沒有更改代碼,因爲accepted answer to the first question使用的是pthread_cond_signal
而不是pthread_cond_broadcast
,而且我領導的聲明是這是對該答案的忠實翻譯。
謝謝!這是一個非常明確的解釋! :) – derekhh 2011-12-16 19:38:07