Can you implement a timer without a “sleep” in it using standard c++/c++11 only?

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<std::mutex> 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<std::mutex> lock{mutex}; // Same instance as above!
    condition_to_be_met = true;
}
cv.notify_one();

Leave a Comment