summaryrefslogtreecommitdiffstats
path: root/mojo/public/cpp/utility/lib/thread.cc
blob: 40f0bdd680c508b8af40d642776531483821f541 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "mojo/public/cpp/utility/thread.h"

#include <assert.h>

namespace mojo {

Thread::Thread() : options_(), thread_(), started_(false), joined_(false) {
}

Thread::Thread(const Options& options)
    : options_(options), thread_(), started_(false), joined_(false) {
}

Thread::~Thread() {
  // If it was started, it must have been joined.
  assert(!started_ || joined_);
}

void Thread::Start() {
  assert(!started_);
  assert(!joined_);

  pthread_attr_t attr;
  int rv = pthread_attr_init(&attr);
  MOJO_ALLOW_UNUSED_LOCAL(rv);
  assert(rv == 0);

  // Non-default stack size?
  if (options_.stack_size() != 0) {
    rv = pthread_attr_setstacksize(&attr, options_.stack_size());
    assert(rv == 0);
  }

  started_ = true;
  rv = pthread_create(&thread_, &attr, &ThreadRunTrampoline, this);
  assert(rv == 0);

  rv = pthread_attr_destroy(&attr);
  assert(rv == 0);
}

void Thread::Join() {
  // Must have been started but not yet joined.
  assert(started_);
  assert(!joined_);

  joined_ = true;
  int rv = pthread_join(thread_, nullptr);
  MOJO_ALLOW_UNUSED_LOCAL(rv);
  assert(rv == 0);
}

// static
void* Thread::ThreadRunTrampoline(void* arg) {
  Thread* self = static_cast<Thread*>(arg);
  self->Run();
  return nullptr;
}

}  // namespace mojo