gpt4 book ai didi

c++ - 使用 future wait_for 时无法检查成员变量,但如果我在线程中休眠,它会起作用

转载 作者:行者123 更新时间:2023-11-30 04:48:42 24 4
gpt4 key购买 nike

我正在使用 std::futurewait_for() 设置超时,等待 zookeeper 连接完成。我一直在线程的 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;
}

关于c++ - 使用 future wait_for 时无法检查成员变量,但如果我在线程中休眠,它会起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55720290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com