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

标签 c++

我正在使用 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/

相关文章:

c++ - Turbo C++程序中的语法错误

c++ - 相同的未更改代码是否可能有时运行有时不运行?

c++ - 用 lambda 初始化 std::unique_ptr 的 std::vector

c++ - 将检查 C++ 项目中是否包含冗余的工具

c++ - QT退出不调用MainWindow析构函数

用于在 vim 中打开文件以便在 Xcode 的终端窗口中进行编辑的 C++ 代码

c++ - 双免腐败

C++ 循环优化和一些错误

c++ - 是否可以将大括号括起来的初始化程序作为宏参数传递?

c++ - 未解析的外部符号