]> git.sesse.net Git - cubemap/blob - thread.h
When warning about unusually long Metacube blocks, use decimal instead of hex.
[cubemap] / thread.h
1 #ifndef _THREAD_H
2 #define _THREAD_H
3
4 #include <signal.h>
5 #include <pthread.h>
6
7 struct timespec;
8
9 // A thread class with start/stop and signal functionality.
10 //
11 // SIGUSR1 is blocked during execution of do_work(), so that you are guaranteed
12 // to receive it when doing wait_for_activity(), and never elsewhere. This means
13 // that you can test whatever status flags you'd want before calling
14 // wait_for_activity(), and then be sure that it actually returns immediately
15 // if a SIGUSR1 (ie., wakeup()) happened, even if it were sent between your test
16 // and the wait_for_activity() call.
17
18 class Thread {
19 public:
20         virtual ~Thread();
21         void run();
22         void stop();
23
24 protected:
25         // Recovers the this pointer, blocks SIGUSR1, and calls do_work().
26         static void *do_work_thunk(void *arg);
27
28         virtual void do_work() = 0;
29
30         // Waits until there is activity of the given type on <fd> (or an error),
31         // or until a wakeup. Returns true if there was actually activity on
32         // the file descriptor.
33         //
34         // If fd is -1, wait until a wakeup or timeout.
35         // if timeout_ts is NULL, there is no timeout.
36         bool wait_for_activity(int fd, short events, const timespec *timeout_ts);
37
38         // Wait until a wakeup.
39         void wait_for_wakeup(const timespec *timeout_ts) { wait_for_activity(-1, 0, timeout_ts); }
40
41         // Make wait_for_activity() return. Note that this is a relatively expensive
42         // operation.
43         void wakeup();
44
45         bool should_stop();
46
47         // The signal set as it were before we blocked SIGUSR1.
48         sigset_t sigset_without_usr1_block;
49
50 private:
51         pthread_t worker_thread;
52
53         // Protects should_stop_status.
54         pthread_mutex_t should_stop_mutex;
55
56         // If this is set, the thread should return as soon as possible from do_work().
57         bool should_stop_status;
58 };
59
60 #endif  // !defined(_THREAD_H)