C++ - Modern way to implement JS's setTimeout

送分小仙女□ 提交于 2021-01-29 10:44:53

问题


I am building an app where requests come in on a zeromq socket. For each request I want to do some processing and send a response, however if a predefined time elapses I want to send the response immediately.

In node.js, I would do something like:

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');
  }
}

Only thing I'm stuck on right now, is setting in the timeout in c++. Don't have a lot of experience with c++, but I am aware there are things in c++11 that would let me do this cleanly.

How should I go about this?


回答1:


std::future is what you are looking for, this can either be used with std::async, std::promise or std::packaged_task. An example with std::async:

#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";
    }
}

Note that the task will continue executing even after the timeout so you'll need to pass in some sort of flag variable if you want to cancel the task before it has finished.



来源:https://stackoverflow.com/questions/51821573/c-modern-way-to-implement-jss-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!