代码之家  ›  专栏  ›  技术社区  ›  user3690467

C++实现JS设置超时的现代方法

  •  0
  • user3690467  · 技术社区  · 7 年前

    我正在构建一个应用程序,其中请求在 zeromq 插座。对于每个请求,我想做一些处理并发送一个响应,但是如果预定义的时间过去了,我想立即发送响应。

    在node.js中,我将执行以下操作:

    async function onRequest(req, sendResponse) {
      let done = false;
    
      setTimeout(() => {
        if (!done) {
          done = true;
          sendResponse('TIMED_OUT');
        }
      }, 10000);
    
      await doSomeWork(req); // do some async work
      if (!done) {
        done = true;
        sendResponse('Work done');
      }
    }
    

    我现在唯一纠结的是在c++中设置超时。对c++没有太多的经验,但我知道c++11中有一些东西可以让我干净利落地完成这项工作。

    我该怎么办?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Alan Birtles    7 年前

    std::future 是你要找的,这个可以和 std::async , std::promise std::packaged_task . 一个例子 标准::异步 :

    #include <iostream>
    #include <string>
    #include <future>
    #include <thread>
    
    int main()
    {
        std::future< int > task = std::async(std::launch::async, []{ std::this_thread::sleep_for(std::chrono::seconds(5)); return 5; } );
        if (std::future_status::ready != task.wait_for(std::chrono::seconds(4)))
        {
            std::cout << "timeout\n";
        }
        else
        {
            std::cout << "result: " << task.get() << "\n";
        }
    }
    

    请注意,即使在超时之后,任务仍将继续执行,因此如果要在任务完成之前取消任务,则需要传入某种标志变量。