1 #ifndef _QUITTABLE_SLEEPER
2 #define _QUITTABLE_SLEEPER 1
4 // A class that assists with fast shutdown of threads. You can set
5 // a flag that says the thread should quit, which it can then check
6 // in a loop -- and if the thread sleeps (using the sleep_* functions
7 // on the class), that sleep will immediately be aborted.
9 // All member functions on this class are thread-safe.
14 class QuittableSleeper {
18 std::lock_guard<std::mutex> l(mu);
19 should_quit_var = true;
20 quit_cond.notify_all();
25 std::lock_guard<std::mutex> l(mu);
26 should_quit_var = false;
29 bool should_quit() const
31 std::lock_guard<std::mutex> l(mu);
32 return should_quit_var;
35 template<class Rep, class Period>
36 void sleep_for(const std::chrono::duration<Rep, Period> &duration)
38 std::chrono::steady_clock::time_point t =
39 std::chrono::steady_clock::now() +
40 std::chrono::duration_cast<std::chrono::steady_clock::duration>(duration);
44 template<class Clock, class Duration>
45 void sleep_until(const std::chrono::time_point<Clock, Duration> &t)
47 std::unique_lock<std::mutex> lock(mu);
48 quit_cond.wait_until(lock, t, [this]{
49 return should_quit_var;
54 mutable std::mutex mu;
55 bool should_quit_var = false;
56 std::condition_variable quit_cond;
59 #endif // !defined(_QUITTABLE_SLEEPER)