Skip to content

Instantly share code, notes, and snippets.

@xylcbd
Created August 31, 2015 01: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 xylcbd/c3565d55940c1df6f4af to your computer and use it in GitHub Desktop.
Save xylcbd/c3565d55940c1df6f4af to your computer and use it in GitHub Desktop.
c++11 timeout handler
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