简体   繁体   English

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

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

Take the following code: 请使用以下代码:

#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();
}

Now, when I build this using clang++ -std=c++11 -pthread foo.cpp everything is fine, it outputs 4 on my machine. 现在,当我使用clang++ -std=c++11 -pthread foo.cpp它时,一切都很好,它在我的机器上输出4 When I build it with g++ -std=c++11 -pthread foo.cpp however I get something very large every time, eg 81513 . 当我使用g++ -std=c++11 -pthread foo.cpp构建它时,我每次都会得到非常大的东西,例如81513 I realize the number of spurious wakeups is undefined, but I was surprised to see it so high. 我意识到虚假唤醒的数量是不确定的,但我很惊讶地看到它如此之高。

Additional information: When I replace the wait_for by a simple wait both clang and g++ output 0 . 附加信息:当我通过简单的wait替换wait_for ,clang和g ++输出0

Is this a bug / feature in g++? 这是g ++中的错误/功能吗? Why is it even different from clang? 为什么它甚至不同于铿锵? Can I get it to behave more reasonably? 我可以让它表现得更合理吗?

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

I managed to get g++-4.8 running, and the problem is gone. 我设法让g ++ - 4.8运行,问题就消失了。 Very weird, seems like a bug in g++-4.7.3, although I wasn't able to reproduce it on another machine. 非常奇怪,似乎是g ++ - 4.7.3中的一个错误,虽然我无法在另一台机器上重现它。

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

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