aboutsummaryrefslogtreecommitdiff
path: root/works/life/operating-system-experiment/Thread.cpp
blob: b91ca694ade7bd45ab5f14ca2e0fbc8525cdf3ee (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
65
66
67
#include "Thread.h"

#include <cassert>
#include <exception>
#include <utility>

namespace cru {
Thread::Thread(Thread &&other) noexcept
    : joined_(other.joined_), thread_handle_(other.thread_handle_) {
  other.joined_ = false;
  other.thread_handle_ = nullptr;
}

Thread &Thread::operator=(Thread &&other) noexcept {
  if (this != &other) {
    joined_ = other.joined_;
    thread_handle_ = other.thread_handle_;
    other.joined_ = false;
    other.thread_handle_ = nullptr;
  }

  return *this;
}

Thread::~Thread() { Destroy(); }

void Thread::Join() {
  assert(thread_handle_);
  joined_ = true;
  WaitForSingleObject(thread_handle_, INFINITE);
}

void Thread::Detach() {
  assert(thread_handle_);
  detached_ = true;
}

void Thread::swap(Thread &other) noexcept {
#ifdef CRU_WINDOWS
  Thread temp = std::move(*this);
  *this = std::move(other);
  other = std::move(temp);
#else
#endif
}

void Thread::Destroy() noexcept {
  if (!detached_ && !joined_ && thread_handle_ != nullptr) {
    std::terminate();
  } else {
    joined_ = false;
    thread_handle_ = nullptr;
  }
}

namespace details {
#ifdef CRU_WINDOWS
DWORD WINAPI ThreadProc(_In_ LPVOID lpParameter) {
  auto p = static_cast<std::function<void()> *>(lpParameter);
  (*p)();
  delete p;
  return 0;
}
#else
#endif
} // namespace details
} // namespace cru