IMPORTANT UPDATE
Note: since this question is specifically about timers, its important to note there is a bug in gcc that if you are using std::condition
C++11 provides us with std::condition_variable
. In your timer you can wait until your condition has been met:
// Somewhere else, e.g. in a header:
std::mutex mutex;
bool condition_to_be_met{false};
std::condition_variable cv;
// In your timer:
// ...
std::unique_lock lock{mutex};
if(!cv.wait_for(lock, std::chrono::milliseconds{timeout_ms}, [this]{return condition_to_be_met;}))
std::cout << "timed out!" << std::endl;
You can find more information here: https://en.cppreference.com/w/cpp/thread/condition_variable
To signal that the condition has been met do this in another thread:
{
std::lock_guard lock{mutex}; // Same instance as above!
condition_to_be_met = true;
}
cv.notify_one();