diff options
author | Andrew Kaster <andrewdkaster@gmail.com> | 2020-12-31 20:56:04 -0700 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2021-01-01 23:01:48 +0100 |
commit | 8d0b4657e7fb0cd3961cdaa54323e0ba38ace7c3 (patch) | |
tree | 4b902639cd8f88c7f2aa080e6b0ca7e1cfb93730 /Libraries/LibThread/Thread.h | |
parent | 986544600a94d0e3ae04cf253ad27b696961f142 (diff) | |
download | serenity-8d0b4657e7fb0cd3961cdaa54323e0ba38ace7c3.zip |
LibThread: Improve semantics of Thread::join, and remove Thread::quit.
Thread::quit was created before the pthread_create_helper in pthread.cpp
that automagically calls pthread_exit from all pthreads after the user's
thread function exits. It is unused, and unecessary now.
Cleanup some logging, and make join return a Result<T, ThreadError>.
This also adds a new type, LibThread::ThreadError as an
AK::DistinctNumeric. Hopefully, this will make it possible to have a
Result<int, ThreadError> and have it compile? It also makes it clear
that the int there is an error at the call site.
By default, the T on join is void, meaning the caller doesn't care about
the return value from the thread.
As Result is a [[nodiscard]] type, also change the current caller of
join to explicitly ignore it.
Move the logging out of join as well, as it's the user's
responsibility whether to log or not.
Diffstat (limited to 'Libraries/LibThread/Thread.h')
-rw-r--r-- | Libraries/LibThread/Thread.h | 27 |
1 files changed, 25 insertions, 2 deletions
diff --git a/Libraries/LibThread/Thread.h b/Libraries/LibThread/Thread.h index 28fba0d78a..7fff078827 100644 --- a/Libraries/LibThread/Thread.h +++ b/Libraries/LibThread/Thread.h @@ -26,13 +26,17 @@ #pragma once +#include <AK/DistinctNumeric.h> #include <AK/Function.h> +#include <AK/Result.h> #include <AK/String.h> #include <LibCore/Object.h> #include <pthread.h> 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<typename T = void> + Result<T, ThreadError> 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<typename T> +Result<T, ThreadError> 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<T>::value) + return {}; + else + return { static_cast<T>(thread_return) }; +} + } |