diff --git a/Libraries/LibThread/Thread.cpp b/Libraries/LibThread/Thread.cpp index 0ac29f4b4f4..7d8fea4af42 100644 --- a/Libraries/LibThread/Thread.cpp +++ b/Libraries/LibThread/Thread.cpp @@ -34,13 +34,15 @@ LibThread::Thread::Thread(Function action, StringView thread_name) , m_action(move(action)) , m_thread_name(thread_name.is_null() ? "" : thread_name) { + register_property("thread_name", [&] { return JsonValue { m_thread_name }; }); + register_property("tid", [&] { return JsonValue { m_tid }; }); } LibThread::Thread::~Thread() { if (m_tid) { - dbg() << "trying to destroy a running thread!"; - join(); + dbgln("Destroying thread \"{}\"({}) while it is still running!", m_thread_name, m_tid); + [[maybe_unused]] auto res = join(); } } @@ -51,7 +53,7 @@ void LibThread::Thread::start() nullptr, [](void* arg) -> void* { Thread* self = static_cast(arg); - size_t exit_code = self->m_action(); + int exit_code = self->m_action(); self->m_tid = 0; return (void*)exit_code; }, @@ -62,22 +64,5 @@ void LibThread::Thread::start() rc = pthread_setname_np(m_tid, m_thread_name.characters()); ASSERT(rc == 0); } - dbg() << "Started a thread, tid = " << m_tid; -} - -void LibThread::Thread::join() -{ - int rc = pthread_join(m_tid, nullptr); - if (rc == 0) - m_tid = 0; - else - warnln("pthread_join: {}", strerror(rc)); -} - -void LibThread::Thread::quit(void* code) -{ - ASSERT(m_tid == pthread_self()); - - m_tid = 0; - pthread_exit(code); + dbgln("Started thread \"{}\", tid = {}", m_thread_name, m_tid); } diff --git a/Libraries/LibThread/Thread.h b/Libraries/LibThread/Thread.h index 28fba0d78a5..7fff078827c 100644 --- a/Libraries/LibThread/Thread.h +++ b/Libraries/LibThread/Thread.h @@ -26,13 +26,17 @@ #pragma once +#include #include +#include #include #include #include namespace LibThread { +TYPEDEF_DISTINCT_ORDERED_ID(int, ThreadError); + class Thread final : public Core::Object { C_OBJECT(Thread); @@ -40,8 +44,11 @@ public: virtual ~Thread(); void start(); - void join(); - void quit(void* code = 0); + + template + Result join(); + + String thread_name() const { return m_thread_name; } pthread_t tid() const { return m_tid; } private: @@ -51,4 +58,20 @@ private: String m_thread_name; }; +template +Result Thread::join() +{ + void* thread_return = nullptr; + int rc = pthread_join(m_tid, &thread_return); + if (rc != 0) { + return ThreadError { rc }; + } + + m_tid = 0; + if constexpr (IsVoid::value) + return {}; + else + return { static_cast(thread_return) }; +} + } diff --git a/Userland/test-pthread.cpp b/Userland/test-pthread.cpp index 991bd539c0b..36914f66340 100644 --- a/Userland/test-pthread.cpp +++ b/Userland/test-pthread.cpp @@ -48,7 +48,7 @@ static void test_once() threads.last().start(); } for (auto& thread : threads) - thread.join(); + [[maybe_unused]] auto res = thread.join(); ASSERT(v.size() == 1); }