1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "mojo/public/cpp/utility/thread.h"
6
7#include <assert.h>
8
9namespace mojo {
10
11Thread::Thread()
12    : options_(),
13      thread_(),
14      started_(false),
15      joined_(false) {
16}
17
18Thread::Thread(const Options& options)
19    : options_(options),
20      thread_(),
21      started_(false),
22      joined_(false) {
23}
24
25Thread::~Thread() {
26  // If it was started, it must have been joined.
27  assert(!started_ || joined_);
28}
29
30void Thread::Start() {
31  assert(!started_);
32  assert(!joined_);
33
34  pthread_attr_t attr;
35  int rv MOJO_ALLOW_UNUSED = pthread_attr_init(&attr);
36  assert(rv == 0);
37
38  // Non-default stack size?
39  if (options_.stack_size() != 0) {
40    rv = pthread_attr_setstacksize(&attr, options_.stack_size());
41    assert(rv == 0);
42  }
43
44  started_ = true;
45  rv = pthread_create(&thread_, &attr, &ThreadRunTrampoline, this);
46  assert(rv == 0);
47
48  rv = pthread_attr_destroy(&attr);
49  assert(rv == 0);
50}
51
52void Thread::Join() {
53  // Must have been started but not yet joined.
54  assert(started_);
55  assert(!joined_);
56
57  joined_ = true;
58  int rv MOJO_ALLOW_UNUSED = pthread_join(thread_, NULL);
59  assert(rv == 0);
60}
61
62// static
63void* Thread::ThreadRunTrampoline(void* arg) {
64  Thread* self = static_cast<Thread*>(arg);
65  self->Run();
66  return NULL;
67}
68
69}  // namespace mojo
70