有没有一种简单的方法在C++ 0x中实现AutoResetEvent?

der*_*khh 7 c++ multithreading autoresetevent c++11

我知道我之前已经问过这个问题:Linux下的AutoResetEvent的C++等价物是什么?

但是,我知道在C++ 0x中,线程库变得更加简单,所以我想再次提出这个问题,是否有一种在C++ 0x中实现AutoResetEvent的简单方法?

How*_*ant 13

以下是使用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();
}
Run Code Online (Sandbox Code Playgroud)

输出:

Hello from the first thread
Hello from other thread!
Run Code Online (Sandbox Code Playgroud)

更新

在下面的评论中,tobsen注意到AutoResetEvent具有语义signal_.notify_all()而不是signal_.notify_one().我的代码并没有改变,因为接受的答案第一个问题使用pthread_cond_signal,而不是pthread_cond_broadcast和我与这是答案的忠实翻译语句领先.

  • 是的。`flag_` 总是在互斥锁的保护下读写,因此不需要(也不应该)是原子的。 (2认同)