繁体   English   中英

使用g ++和clang ++在condition_variable上进行虚假唤醒

[英]Spurious wakeups on condition_variable with g++ and clang++

请使用以下代码:

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>

using namespace std;

int main() {
  mutex m;
  condition_variable c;

  bool fired = false;
  int i = 0;

  // This thread counts the times the condition_variable woke up.
  // If no spurious wakeups occur it should be close to 5.
  thread t([&]() {
    unique_lock<mutex> l(m);
    while (!fired) {
      c.wait_for(l, chrono::milliseconds(100));
      ++i;
    }
  });

  // Here we wait for 500ms, then signal the other thread to stop
  this_thread::sleep_for(chrono::milliseconds(500));
  {
    unique_lock<mutex> l(m);
    fired = true;
    c.notify_all();
    cout << i << endl;
  }
  t.join();
}

现在,当我使用clang++ -std=c++11 -pthread foo.cpp它时,一切都很好,它在我的机器上输出4 当我使用g++ -std=c++11 -pthread foo.cpp构建它时,我每次都会得到非常大的东西,例如81513 我意识到虚假唤醒的数量是不确定的,但我很惊讶地看到它如此之高。

附加信息:当我通过简单的wait替换wait_for ,clang和g ++输出0

这是g ++中的错误/功能吗? 为什么它甚至不同于铿锵? 我可以让它表现得更合理吗?

另外: gcc version 4.7.3 (Debian 4.7.3-4)

我设法让g ++ - 4.8运行,问题就消失了。 非常奇怪,似乎是g ++ - 4.7.3中的一个错误,虽然我无法在另一台机器上重现它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM