Last active
April 13, 2019 16:51
-
-
Save utilForever/67c2667e3cd411277332310bdb0c0276 to your computer and use it in GitHub Desktop.
Timeout function example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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