Timeouts in C++
Timeouts are important for programs that connect to external resources or that otherwise need to bound execution time. Implementing timeouts in C++ is possible using threads and chrono library.
#include <iostream>
#include <chrono>
#include <thread>
#include <future>
int main() {
// For our example, suppose we're executing an external
// call that returns its result after 2s. We'll use a
// std::future to represent this asynchronous operation.
auto c1 = std::async(std::launch::async, []() {
std::this_thread::sleep_for(std::chrono::seconds(2));
return std::string("result 1");
});
// Here's the implementation of a timeout.
// We use future::wait_for to wait for the result
// with a timeout of 1s.
if (c1.wait_for(std::chrono::seconds(1)) == std::future_status::ready) {
std::cout << c1.get() << std::endl;
} else {
std::cout << "timeout 1" << std::endl;
}
// If we allow a longer timeout of 3s, then the future
// will complete and we'll print the result.
auto c2 = std::async(std::launch::async, []() {
std::this_thread::sleep_for(std::chrono::seconds(2));
return std::string("result 2");
});
if (c2.wait_for(std::chrono::seconds(3)) == std::future_status::ready) {
std::cout << c2.get() << std::endl;
} else {
std::cout << "timeout 2" << std::endl;
}
return 0;
}
Running this program shows the first operation timing out and the second succeeding.
$ g++ -std=c++11 timeouts.cpp -o timeouts
$ ./timeouts
timeout 1
result 2
In this C++ version, we use std::async
to create asynchronous tasks that simulate long-running operations. We then use std::future::wait_for
to implement timeouts. The wait_for
function allows us to specify a duration to wait for the future to complete. If the future completes within the specified time, we can get the result. Otherwise, we handle the timeout case.
Note that C++ doesn’t have built-in channels like some other languages, so we use futures and promises to achieve similar functionality. The std::async
function returns a std::future
, which we can use to retrieve the result of the asynchronous operation.
The chrono
library is used for time-related operations, allowing us to specify durations and sleep for certain periods of time.
This approach provides a way to implement timeouts in C++, although it’s not as concise as in some other languages due to the more verbose nature of C++ and its standard library.