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

后端 未结 3 1285
借酒劲吻你
借酒劲吻你 2021-02-05 01:37

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

3条回答
  •  礼貌的吻别
    2021-02-05 02:07

    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();
    

提交回复
热议问题