简体   繁体   中英

boost::interprocess::interprocess_condition::timed_wait waits forever

I've the following minimal example:

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

What I was expecting is that inside the lambda function the interprocess_condition variable ic waits for 100 milliseconds, and then the function continues. Instead the condition waits for the notify called in second thread.

What I' doing wrong? How should I use in correct way timed_wait in order to wait the desired amount of time?

I'm using boost version 1.72.0.

I've found the solution. I need to use boost::posix_time::microsec_clock::universal_time rather than boost::posix_time::microsec_clock::local_time .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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