]> git.sesse.net Git - nageru/blob - quittable_sleeper.h
Make some more sleeps interruptable.
[nageru] / quittable_sleeper.h
1 #ifndef _QUITTABLE_SLEEPER
2 #define _QUITTABLE_SLEEPER 1
3
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.
8 //
9 // All member functions on this class are thread-safe.
10
11 #include <chrono>
12 #include <mutex>
13
14 class QuittableSleeper {
15 public:
16         void quit()
17         {
18                 std::lock_guard<std::mutex> l(mu);
19                 should_quit_var = true;
20                 quit_cond.notify_all();
21         }
22
23         void unquit()
24         {
25                 std::lock_guard<std::mutex> l(mu);
26                 should_quit_var = false;
27         }
28
29         bool should_quit() const
30         {
31                 std::lock_guard<std::mutex> l(mu);
32                 return should_quit_var;
33         }
34
35         template<class Rep, class Period>
36         void sleep_for(const std::chrono::duration<Rep, Period> &duration)
37         {
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);
41                 sleep_until(t);
42         }
43
44         template<class Clock, class Duration>
45         void sleep_until(const std::chrono::time_point<Clock, Duration> &t)
46         {
47                 std::unique_lock<std::mutex> lock(mu);
48                 quit_cond.wait_until(lock, t, [this]{
49                         return should_quit_var;
50                 });
51         }
52
53 private:
54         mutable std::mutex mu;
55         bool should_quit_var = false;
56         std::condition_variable quit_cond;
57 };
58
59 #endif  // !defined(_QUITTABLE_SLEEPER)