![](/img/trans.png)
[英]std::conditional_variable::wait_for, std::thread::sleep_for on Windows are affected by adjusting clock
[英]can't check a member variable when using future wait_for, but if I sleep in thread, it works
我正在使用std::future
和wait_for()
设置超时,等待动物园管理员连接完成。 我一直在线程的 while 循环中检查connected_
。 如果我不在循环中休眠, wait_for()
总是返回超时,但我确定已设置connected_
。 如果我在 while 循环中睡眠几毫秒,它运行良好。 connection_timeout_
的时间足够长。 那么我的代码有什么问题?
std::future<int> fut = std::async(std::launch::async, [this]{
while(true){
usleep(1000);//if delete this line, I get timeout always
if(connected_){
return 0;
}
}
});
auto status = fut.wait_for(std::chrono::duration<int, std::milli>{connection_timeout_});
if(status == std::future_status::deferred){
LOGGER_ERROR(Log::GetLog(), "wait for zk connection: deferred");
return -1;
}else if(status == std::future_status::timeout){
LOGGER_ERROR(Log::GetLog(), "wait for zk connection: timeout");
return -1;
}else{// status == std::future_status::ready
LOGGER_INFO(Log::GetLog(), "wait for zk connection: connected");
}
你的代码对我来说似乎没问题。 似乎罪魁祸首可能是connected_
一直没有在超时之前设置。 这是一个测试代码:
std::atomic<bool> connected_ = false;
std::chrono::milliseconds connection_timeout_ = std::chrono::milliseconds(100);
struct foo {
std::future<int> fut = std::async(std::launch::async, [this] {
while (true) {
std::this_thread::sleep_for(std::chrono::microseconds(1000));
if (connected_) {
return 0;
}
}
});
};
int main()
{
foo f;
std::thread([]() {
std::this_thread::sleep_for(std::chrono::milliseconds(50)); // connected_ set set after: 500 = timeout , 50 = connected
connected_ = true;
}).detach();
auto status = f.fut.wait_for(std::chrono::duration<int, std::milli>(connection_timeout_));
if (status == std::future_status::deferred) {
std::cout<< "wait for zk connection: deferred\n";
return -1;
}
else if (status == std::future_status::timeout) {
std::cout << "wait for zk connection: timeout\n";
return -1;
}
else if ( status == std::future_status::ready) {
std::cout << "wait for zk connection: connected\n";
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.