blob: 80b45e1466f6ed7fa64e0a7742dc3c89393c6596 [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>
Brian Silvermand4c48322014-09-06 21:17:29 -04005#include <atomic>
Brian Silverman653491d2014-05-13 16:53:29 -07006
Brian Silvermand4c48322014-09-06 21:17:29 -04007#include <pthread.h>
8
Brian Silverman653491d2014-05-13 16:53:29 -07009#include "aos/common/macros.h"
Brian Silverman798c7782013-03-28 16:48:02 -070010
11namespace aos {
12namespace util {
13
14// A nice wrapper around a pthreads thread.
15//
16// TODO(aschuh): Test this.
17class Thread {
18 public:
19 Thread();
Brian Silverman3d5e6972013-09-06 17:30:36 -070020 virtual ~Thread();
Brian Silverman798c7782013-03-28 16:48:02 -070021
22 // Actually creates the thread.
23 void Start();
24
25 // Asks the code to stop and then waits until it has done so.
26 void Join();
27
Brian Silverman653491d2014-05-13 16:53:29 -070028 // Waits until the code has stopped. Does not ask it to do so.
29 void WaitUntilDone();
30
Brian Silverman798c7782013-03-28 16:48:02 -070031 protected:
32 // Subclasses need to call this periodically if they are going to loop to
33 // check whether they have been asked to stop.
34 bool should_continue() {
Brian Silvermand4c48322014-09-06 21:17:29 -040035 return !should_terminate_.load();
Brian Silverman798c7782013-03-28 16:48:02 -070036 }
37
38 private:
39 // Where subclasses actually do something.
40 //
41 // They should not block for long periods of time without checking
42 // should_continue().
43 virtual void Run() = 0;
44
45 static void *StaticRun(void *self);
46
47 pthread_t thread_;
48 bool started_;
49 bool joined_;
Brian Silvermand4c48322014-09-06 21:17:29 -040050 ::std::atomic_bool should_terminate_;
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_