【发布时间】: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