Search code examples
javascriptc++multithreadingc++11timeout

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


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?


Solution

  • 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.