7

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

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

4

1 回答 1

14

以下是对使用 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()代替的语义signal_.notify_one()。我没有更改代码,因为使用的第一个问题的公认答案pthread_cond_signal与我相反pthread_cond_broadcast,我首先声明这是对该答案的忠实翻译。

于 2011-12-16T18:45:46.597 回答