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メモが表示されます。最初の質問に対する受け入れられた回答が反対に使用されたため、コードを変更していません。これはその回答の忠実な翻訳であるという声明を先導しています。AutoResetEventsignal_.notify_all()signal_.notify_one()pthread_cond_signalpthread_cond_broadcast

于 2011-12-16T18:45:46.597 に答える