X-Git-Url: https://git.sesse.net/?a=blobdiff_plain;f=quittable_sleeper.h;fp=quittable_sleeper.h;h=0000000000000000000000000000000000000000;hb=392f9d1ccb835c05a3874c4bea163788b2c37024;hp=6c449a7b3c6e9a24be098b0f532093e7431ef53b;hpb=330ca2f0052b06d91004c6ceb73cd57ab95e7fe1;p=nageru diff --git a/quittable_sleeper.h b/quittable_sleeper.h deleted file mode 100644 index 6c449a7..0000000 --- a/quittable_sleeper.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef _QUITTABLE_SLEEPER -#define _QUITTABLE_SLEEPER 1 - -// A class that assists with fast shutdown of threads. You can set -// a flag that says the thread should quit, which it can then check -// in a loop -- and if the thread sleeps (using the sleep_* functions -// on the class), that sleep will immediately be aborted. -// -// All member functions on this class are thread-safe. - -#include -#include -#include - -class QuittableSleeper { -public: - void quit() - { - std::lock_guard l(mu); - should_quit_var = true; - quit_cond.notify_all(); - } - - void unquit() - { - std::lock_guard l(mu); - should_quit_var = false; - } - - void wakeup() - { - std::lock_guard l(mu); - should_wakeup_var = true; - quit_cond.notify_all(); - } - - bool should_quit() const - { - std::lock_guard l(mu); - return should_quit_var; - } - - // Returns false if woken up early. - template - bool sleep_for(const std::chrono::duration &duration) - { - std::chrono::steady_clock::time_point t = - std::chrono::steady_clock::now() + - std::chrono::duration_cast(duration); - return sleep_until(t); - } - - // Returns false if woken up early. - template - bool sleep_until(const std::chrono::time_point &t) - { - std::unique_lock lock(mu); - quit_cond.wait_until(lock, t, [this]{ - return should_quit_var || should_wakeup_var; - }); - if (should_wakeup_var) { - should_wakeup_var = false; - return false; - } - return !should_quit_var; - } - -private: - mutable std::mutex mu; - bool should_quit_var = false, should_wakeup_var = false; - std::condition_variable quit_cond; -}; - -#endif // !defined(_QUITTABLE_SLEEPER)