blob: bfb1f51e421be1f5e55fe3fef4d9fedc22ff556d [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;
Brian Silvermand4c48322014-09-06 21:17:29 -040027 should_terminate_.store(true);
Brian Silverman653491d2014-05-13 16:53:29 -070028 CHECK(pthread_join(thread_, NULL) == 0);
29}
30
31void Thread::WaitUntilDone() {
32 CHECK(!joined_ && started_);
33 joined_ = true;
34 CHECK(pthread_join(thread_, NULL) == 0);
Brian Silverman798c7782013-03-28 16:48:02 -070035}
36
37void *Thread::StaticRun(void *self) {
38 static_cast<Thread *>(self)->Run();
39 return NULL;
40}
41
42} // namespace util
43} // namespace aos