blob: dbb638e25057968715784bb14ba1c21df72efba7 [file] [log] [blame]
Brian Silverman798c7782013-03-28 16:48:02 -07001#include "aos/common/util/thread.h"
2
3#include <pthread.h>
Brian Silverman653491d2014-05-13 16:53:29 -07004
5#include "aos/common/logging/logging.h"
Brian Silverman798c7782013-03-28 16:48:02 -07006
7namespace aos {
8namespace util {
9
10Thread::Thread() : started_(false), joined_(false), should_terminate_(false) {}
11
12Thread::~Thread() {
13 if (started_ && !joined_) {
Brian Silverman653491d2014-05-13 16:53:29 -070014 CHECK(false);
Brian Silverman798c7782013-03-28 16:48:02 -070015 }
16}
17
18void Thread::Start() {
Brian Silverman653491d2014-05-13 16:53:29 -070019 CHECK(!started_);
Brian Silverman798c7782013-03-28 16:48:02 -070020 started_ = true;
Brian Silverman653491d2014-05-13 16:53:29 -070021 CHECK(pthread_create(&thread_, NULL, &Thread::StaticRun, this) == 0);
Brian Silverman798c7782013-03-28 16:48:02 -070022}
23
24void Thread::Join() {
Brian Silverman653491d2014-05-13 16:53:29 -070025 CHECK(!joined_ && started_);
Brian Silverman798c7782013-03-28 16:48:02 -070026 joined_ = true;
27 {
28 MutexLocker locker(&should_terminate_mutex_);
29 should_terminate_ = true;
30 }
Brian Silverman653491d2014-05-13 16:53:29 -070031 CHECK(pthread_join(thread_, NULL) == 0);
32}
33
34void Thread::WaitUntilDone() {
35 CHECK(!joined_ && started_);
36 joined_ = true;
37 CHECK(pthread_join(thread_, NULL) == 0);
Brian Silverman798c7782013-03-28 16:48:02 -070038}
39
40void *Thread::StaticRun(void *self) {
41 static_cast<Thread *>(self)->Run();
42 return NULL;
43}
44
45} // namespace util
46} // namespace aos