Skip to content

Instantly share code, notes, and snippets.

@utilForever
Last active April 13, 2019 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save utilForever/67c2667e3cd411277332310bdb0c0276 to your computer and use it in GitHub Desktop.
Save utilForever/67c2667e3cd411277332310bdb0c0276 to your computer and use it in GitHub Desktop.
Timeout function example
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
using namespace std::chrono_literals;
int Func()
{
std::this_thread::sleep_for(10s);
return 1;
}
int FuncWrapper()
{
std::mutex m;
std::condition_variable cv;
int retValue;
std::thread t([&cv, &retValue]() {
retValue = Func();
cv.notify_one();
});
t.detach();
{
std::unique_lock<std::mutex> l(m);
if (cv.wait_for(l, 1s) == std::cv_status::timeout)
{
throw std::runtime_error("Timeout");
}
}
return retValue;
}
int main()
{
bool timedOut = false;
try
{
FuncWrapper();
}
catch (std::runtime_error& e)
{
std::cout << e.what() << std::endl;
timedOut = true;
}
if (!timedOut)
{
std::cout << "Success" << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment