Brian Silverman | 798c778 | 2013-03-28 16:48:02 -0700 | [diff] [blame] | 1 | #ifndef AOS_COMMON_UTIL_THREAD_H_ |
| 2 | #define AOS_COMMON_UTIL_THREAD_H_ |
| 3 | |
| 4 | #include "aos/common/mutex.h" |
| 5 | |
| 6 | namespace aos { |
| 7 | namespace util { |
| 8 | |
| 9 | // A nice wrapper around a pthreads thread. |
| 10 | // |
| 11 | // TODO(aschuh): Test this. |
| 12 | class Thread { |
| 13 | public: |
| 14 | Thread(); |
| 15 | ~Thread(); |
| 16 | |
| 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_ |