From 644f5ec160caf09b99901164b874274b3f4df62b Mon Sep 17 00:00:00 2001 From: Andrew Kaster Date: Thu, 31 Dec 2020 00:57:44 -0700 Subject: [PATCH] LibThread: Give Thread std::jthread semantics Because pthread_create will always call pthread_exit internally before exiting the thread function, we can remove the odd requirement that the user's thread function must call Thread::quit internally. Make Thread::join clear m_tid on success, and print to stderr on failure. Call join from ~Thread(). Now if you write an infinite loop in your thread in an application and don't have an exit condition, you will block in the thread's destructor forever. Time for stop_token? :) --- Libraries/LibThread/Thread.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Libraries/LibThread/Thread.cpp b/Libraries/LibThread/Thread.cpp index 658a5d1163..0ac29f4b4f 100644 --- a/Libraries/LibThread/Thread.cpp +++ b/Libraries/LibThread/Thread.cpp @@ -26,6 +26,7 @@ #include #include +#include #include LibThread::Thread::Thread(Function action, StringView thread_name) @@ -39,7 +40,7 @@ LibThread::Thread::~Thread() { if (m_tid) { dbg() << "trying to destroy a running thread!"; - ASSERT_NOT_REACHED(); + join(); } } @@ -66,7 +67,11 @@ void LibThread::Thread::start() void LibThread::Thread::join() { - pthread_join(m_tid, nullptr); + 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)