File: thread.h

package info (click to toggle)
cubemap 1.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 428 kB
  • sloc: cpp: 4,431; sh: 114; perl: 102; makefile: 60
file content (60 lines) | stat: -rw-r--r-- 1,748 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#ifndef _THREAD_H
#define _THREAD_H

#include <signal.h>
#include <pthread.h>

struct timespec;

// A thread class with start/stop and signal functionality.
//
// SIGUSR1 is blocked during execution of do_work(), so that you are guaranteed
// to receive it when doing wait_for_activity(), and never elsewhere. This means
// that you can test whatever status flags you'd want before calling
// wait_for_activity(), and then be sure that it actually returns immediately
// if a SIGUSR1 (ie., wakeup()) happened, even if it were sent between your test
// and the wait_for_activity() call.

class Thread {
public:
	virtual ~Thread();
	void run();
	void stop();

protected:
	// Recovers the this pointer, blocks SIGUSR1, and calls do_work().
	static void *do_work_thunk(void *arg);

	virtual void do_work() = 0;

	// Waits until there is activity of the given type on <fd> (or an error),
	// or until a wakeup. Returns true if there was actually activity on
	// the file descriptor.
	//
	// If fd is -1, wait until a wakeup or timeout.
	// if timeout_ts is NULL, there is no timeout.
	bool wait_for_activity(int fd, short events, const timespec *timeout_ts);

	// Wait until a wakeup.
	void wait_for_wakeup(const timespec *timeout_ts) { wait_for_activity(-1, 0, timeout_ts); }

	// Make wait_for_activity() return. Note that this is a relatively expensive
	// operation.
	void wakeup();

	bool should_stop();

	// The signal set as it were before we blocked SIGUSR1.
	sigset_t sigset_without_usr1_block;

private:
	pthread_t worker_thread;

	// Protects should_stop_status.
	pthread_mutex_t should_stop_mutex;

	// If this is set, the thread should return as soon as possible from do_work().
	bool should_stop_status;
};

#endif  // !defined(_THREAD_H)