【问题标题】:boost::interprocess::interprocess_condition::timed_wait waits foreverboost::interprocess::interprocess_condition::timed_wait 永远等待
【发布时间】:2020-07-03 20:24:58
【问题描述】:

我有以下最小示例:

#include <iostream>
#include <boost/thread.hpp>
#include <boost/interprocess/sync/interprocess_condition.hpp>
#include <boost/interprocess/sync/interprocess_mutex.hpp>


int main(int argc, char* argv[]) {
  boost::interprocess::interprocess_condition ic;
  boost::interprocess::interprocess_mutex im;
  bool test = false;
  auto testFunction = [&ic, &im, &test]() {
    boost::unique_lock lk(im);
    auto tin = boost::posix_time::microsec_clock::local_time();
    auto waitTime = tin + boost::posix_time::milliseconds(100);
    if (!ic.timed_wait(lk, waitTime)) {
      test = false;
    }
    else {
      test = true;
    }
  };

  auto notifyFunction = [&ic]() {
    ic.notify_all();
  };

  boost::thread t(testFunction);
  boost::this_thread::sleep_for(boost::chrono::milliseconds(2000));
  boost::thread t2(notifyFunction);
  t.join();
  t2.join();
  std::cout << "Result is: " << std::boolalpha << test << std::endl;
  return 0;
}

我所期待的是,在 lambda 函数内部,interprocess_condition 变量 ic 等待 100 毫秒,然后函数继续。相反,条件等待在第二个线程中调用的通知。

我做错了什么?我应该如何正确使用timed_wait 才能等待所需的时间?

我使用的是 boost 1.72.0 版。

【问题讨论】:

    标签: c++ multithreading boost thread-synchronization boost-interprocess


    【解决方案1】:

    我找到了解决方案。我需要使用boost::posix_time::microsec_clock::universal_time 而不是boost::posix_time::microsec_clock::local_time

    【讨论】:

      猜你喜欢
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      • 2012-02-24
      • 1970-01-01
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      相关资源
      最近更新 更多