Created
August 31, 2015 01:51
-
-
Save xylcbd/c3565d55940c1df6f4af to your computer and use it in GitHub Desktop.
c++11 timeout handler
This file contains 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
template<typename CALLBACKTYPE,typename... ARGS> | |
class TimeoutHandler | |
{ | |
public: | |
TimeoutHandler(const int _timeout/*ms*/,CALLBACKTYPE _callback, ARGS... _args) | |
{ | |
std::thread([](TimeoutHandler* this_object,int _timeout, CALLBACKTYPE _callback, ARGS... _args) | |
{ | |
std::this_thread::sleep_for(std::chrono::milliseconds(_timeout)); | |
if (!this_object->exit_flag) | |
{ | |
_callback(_args...); | |
} | |
else | |
{ | |
//can't use this_object | |
} | |
}, this, _timeout, _callback, _args...).detach(); | |
} | |
virtual ~TimeoutHandler() | |
{ | |
exit_flag = true; | |
} | |
private: | |
std::atomic<bool> exit_flag = false; | |
}; | |
void long_excute_function() | |
{ | |
bool exit_flag = false; | |
TimeoutHandler<std::function<void()>> timeout_handler(1000, | |
[&](){ | |
exit_flag = true; | |
}); | |
while (!exit_flag) | |
{ | |
std::cout << "long_excute_function" << std::endl; | |
std::this_thread::sleep_for(std::chrono::milliseconds(10)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment