blob: ab6f09c5f01b5deff5debb172609d6a58c25a934 [file] [log] [blame]
Brian Silverman798c7782013-03-28 16:48:02 -07001#ifndef AOS_COMMON_UTIL_THREAD_H_
2#define AOS_COMMON_UTIL_THREAD_H_
3
4#include "aos/common/mutex.h"
5
6namespace aos {
7namespace util {
8
9// A nice wrapper around a pthreads thread.
10//
11// TODO(aschuh): Test this.
12class Thread {
13 public:
14 Thread();
Brian Silverman3d5e6972013-09-06 17:30:36 -070015 virtual ~Thread();
Brian Silverman798c7782013-03-28 16:48:02 -070016
17 // Actually creates the thread.
18 void Start();
19
20 // Asks the code to stop and then waits until it has done so.
21 void Join();
22
23 protected:
24 // Subclasses need to call this periodically if they are going to loop to
25 // check whether they have been asked to stop.
26 bool should_continue() {
27 MutexLocker locker(&should_terminate_mutex_);
28 return !should_terminate_;
29 }
30
31 private:
32 // Where subclasses actually do something.
33 //
34 // They should not block for long periods of time without checking
35 // should_continue().
36 virtual void Run() = 0;
37
38 static void *StaticRun(void *self);
39
40 pthread_t thread_;
41 bool started_;
42 bool joined_;
43 bool should_terminate_;
44 Mutex should_terminate_mutex_;
45};
46
47} // namespace util
48} // namespace aos
49
50#endif // AOS_COMMON_UTIL_THREAD_H_