Brian Silverman | 798c778 | 2013-03-28 16:48:02 -0700 | [diff] [blame] | 1 | #include "aos/common/util/thread.h" |
| 2 | |
| 3 | #include <pthread.h> |
| 4 | #include <assert.h> |
| 5 | |
| 6 | namespace aos { |
| 7 | namespace util { |
| 8 | |
| 9 | Thread::Thread() : started_(false), joined_(false), should_terminate_(false) {} |
| 10 | |
| 11 | Thread::~Thread() { |
| 12 | if (started_ && !joined_) { |
| 13 | assert(false); |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | void Thread::Start() { |
| 18 | assert(!started_); |
| 19 | started_ = true; |
| 20 | assert(pthread_create(&thread_, NULL, &Thread::StaticRun, this) == 0); |
| 21 | } |
| 22 | |
| 23 | void Thread::Join() { |
| 24 | assert(!joined_ && started_); |
| 25 | joined_ = true; |
| 26 | { |
| 27 | MutexLocker locker(&should_terminate_mutex_); |
| 28 | should_terminate_ = true; |
| 29 | } |
| 30 | assert(pthread_join(thread_, NULL) == 0); |
| 31 | } |
| 32 | |
| 33 | void *Thread::StaticRun(void *self) { |
| 34 | static_cast<Thread *>(self)->Run(); |
| 35 | return NULL; |
| 36 | } |
| 37 | |
| 38 | } // namespace util |
| 39 | } // namespace aos |