blob: 97123d510e33f53e2b63b75daf4ee510658917ea [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
Brian Silverman653491d2014-05-13 16:53:29 -07004#include <functional>
5
Brian Silverman798c7782013-03-28 16:48:02 -07006#include "aos/common/mutex.h"
Brian Silverman653491d2014-05-13 16:53:29 -07007#include "aos/common/macros.h"
Brian Silverman798c7782013-03-28 16:48:02 -07008
9namespace aos {
10namespace util {
11
12// A nice wrapper around a pthreads thread.
13//
14// TODO(aschuh): Test this.
15class Thread {
16 public:
17 Thread();
Brian Silverman3d5e6972013-09-06 17:30:36 -070018 virtual ~Thread();
Brian Silverman798c7782013-03-28 16:48:02 -070019
20 // Actually creates the thread.
21 void Start();
22
23 // Asks the code to stop and then waits until it has done so.
24 void Join();
25
Brian Silverman653491d2014-05-13 16:53:29 -070026 // Waits until the code has stopped. Does not ask it to do so.
27 void WaitUntilDone();
28
Brian Silverman798c7782013-03-28 16:48:02 -070029 protected:
30 // Subclasses need to call this periodically if they are going to loop to
31 // check whether they have been asked to stop.
32 bool should_continue() {
33 MutexLocker locker(&should_terminate_mutex_);
34 return !should_terminate_;
35 }
36
37 private:
38 // Where subclasses actually do something.
39 //
40 // They should not block for long periods of time without checking
41 // should_continue().
42 virtual void Run() = 0;
43
44 static void *StaticRun(void *self);
45
46 pthread_t thread_;
47 bool started_;
48 bool joined_;
49 bool should_terminate_;
50 Mutex should_terminate_mutex_;
Brian Silverman653491d2014-05-13 16:53:29 -070051
52 DISALLOW_COPY_AND_ASSIGN(Thread);
53};
54
55class FunctionThread : public Thread {
56 public:
57 FunctionThread(::std::function<void(FunctionThread *)> function)
58 : function_(function) {}
59
60 private:
61 virtual void Run() override {
62 function_(this);
63 }
64
65 const ::std::function<void(FunctionThread *)> function_;
Brian Silverman798c7782013-03-28 16:48:02 -070066};
67
68} // namespace util
69} // namespace aos
70
71#endif // AOS_COMMON_UTIL_THREAD_H_