c ++ wait_until奇怪的超时行为

时间:2017-12-07 10:49:58

标签: c++ linux macos c++11

我试图用C ++编写一种线程池。代码在OSX中运行良好,但在Linux下我遇到了一种奇怪的行为。 经过一些调试后,我发现问题是由于调用std :: condition_variable :: wait_until,我必须以错误的方式进行。

使用下面的代码,我希望循环每三秒循环一次:

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

using namespace std;

typedef std::chrono::steady_clock                           my_clock;
typedef std::chrono::duration<float, std::ratio<1> >        seconds_duration;
typedef std::chrono::time_point<my_clock, seconds_duration> timepoint;

timepoint my_begin = my_clock::now();

float timepointToFloat(timepoint time) {
  return time.time_since_epoch().count() - my_begin.time_since_epoch().count();
}

void printNow(std::string mess) {
  timepoint now = my_clock::now();
  cout << timepointToFloat(now) << " " << mess  << endl;;
};

void printNow(std::string mess, timepoint time ) {
  timepoint now = my_clock::now();
  cout << timepointToFloat(now) << " " << mess  << " " << timepointToFloat(time) << endl;;
};

int main() {
  mutex _global_mutex;
  condition_variable _awake_global_execution;
  auto check_predicate = [](){
    cout << "predicate called" << endl;
    return false;
  };

  while (true) {
    { // Expected to loop every three seconds
      unique_lock<mutex> lock(_global_mutex);
      timepoint planned_awake = my_clock::now() + seconds_duration(3);
      printNow("wait until", planned_awake);
      _awake_global_execution.wait_until(lock, planned_awake, check_predicate);
    }
    printNow("finish wait, looping");
  }

  return 0;
}

然而,有时我得到输出:

<X> wait until <X+3>
predicate called
(...hangs here for a long time)

(其中X是一个数字),所以似乎三秒后没有安排超时。有时我得到:

<X> wait until <X+3>
predicate called
predicate called
<X> finish wait, looping
<X> wait until <X+3> (another loop)
predicate called
predicate called
<X> finish wait, looping
(...continue looping without waiting)

所以似乎超时是在一小段时间后安排的。我想我会用超时时间点弄乱一些东西,但我无法弄清楚我做错了什么。

如果它可能是相关的,这个代码在OSX中工作正常,而在Linux中(Ubuntu 16.04,gcc 5.4,使用&#34编译; g ++ main.cc -std = c ++ 11 -pthread&#34;)I& #39;我遇到了奇怪的行为。

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:0)

尝试将超时时间延长到时钟的持续时间:

auto planned_awake = my_clock::now() + 
                     std::chrono::duration_cast<my_clock::duration>(secon‌​ds_duration(3));