From 8bdb5db67fa3eeda755511f91fd257bde548a18f Mon Sep 17 00:00:00 2001 From: crupest Date: Wed, 9 Jun 2021 22:28:01 +0800 Subject: import(life): ... --- works/life/operating-system-experiment/Thread.cpp | 53 ++++++++++++++++++++--- 1 file changed, 48 insertions(+), 5 deletions(-) (limited to 'works/life/operating-system-experiment/Thread.cpp') diff --git a/works/life/operating-system-experiment/Thread.cpp b/works/life/operating-system-experiment/Thread.cpp index b91ca69..8230c1c 100644 --- a/works/life/operating-system-experiment/Thread.cpp +++ b/works/life/operating-system-experiment/Thread.cpp @@ -2,21 +2,36 @@ #include #include +#include #include namespace cru { Thread::Thread(Thread &&other) noexcept - : joined_(other.joined_), thread_handle_(other.thread_handle_) { + : detached_(other.detached_), joined_(other.joined_), +#ifdef CRU_WINDOWS + thread_handle_(other.thread_handle_) +#else + thread_(std::move(other.thread_)) +#endif +{ other.joined_ = false; +#ifdef CRU_WINDOWS other.thread_handle_ = nullptr; -} +#endif +} // namespace cru Thread &Thread::operator=(Thread &&other) noexcept { if (this != &other) { + detached_ = other.detached_; joined_ = other.joined_; +#ifdef CRU_WINDOWS thread_handle_ = other.thread_handle_; - other.joined_ = false; other.thread_handle_ = nullptr; +#else + thread_ = std::move(other.thread_); +#endif + other.detached_ = false; + other.joined_ = false; } return *this; @@ -25,13 +40,23 @@ Thread &Thread::operator=(Thread &&other) noexcept { Thread::~Thread() { Destroy(); } void Thread::Join() { - assert(thread_handle_); joined_ = true; +#ifdef CRU_WINDOWS + assert(thread_handle_); WaitForSingleObject(thread_handle_, INFINITE); +#else + assert(thread_); + auto c = pthread_join(*thread_, nullptr); + assert(c == 0); +#endif } void Thread::Detach() { +#ifdef CRU_WINDOWS assert(thread_handle_); +#else + assert(thread_); +#endif detached_ = true; } @@ -45,11 +70,22 @@ void Thread::swap(Thread &other) noexcept { } void Thread::Destroy() noexcept { - if (!detached_ && !joined_ && thread_handle_ != nullptr) { + if (!detached_ && !joined_ && +#ifdef CRU_WINDOWS + thread_handle_ != nullptr +#else + thread_ != nullptr +#endif + ) { std::terminate(); } else { + detached_ = false; joined_ = false; +#ifdef CRU_WINDOWS thread_handle_ = nullptr; +#else + thread_ = nullptr; +#endif } } @@ -62,6 +98,13 @@ DWORD WINAPI ThreadProc(_In_ LPVOID lpParameter) { return 0; } #else +void *ThreadProc(void *data) { + auto p = static_cast *>(data); + (*p)(); + delete p; + return nullptr; +} + #endif } // namespace details } // namespace cru \ No newline at end of file -- cgit v1.2.3