From aff64b6a03ac4992dac34f22513eefaca2f77e9f Mon Sep 17 00:00:00 2001 From: Zaggy1024 Date: Sun, 6 Aug 2023 01:31:42 -0500 Subject: [PATCH] LibThreading: Make Thread keep itself alive while its action is running Previously, a `Thread` could be deleted while its action was running, even if it was running detached. By changing it to be atomically reference counted, and incrementing the count when starting the action, we can keep the Thread and its running action `Function` alive until it exits. Thus, detached `Thread` objects can be deleted by the thread creating them and allowed to die naturally. --- Userland/Libraries/LibThreading/Thread.cpp | 7 +++---- Userland/Libraries/LibThreading/Thread.h | 3 ++- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Userland/Libraries/LibThreading/Thread.cpp b/Userland/Libraries/LibThreading/Thread.cpp index d8ac15a26c8..ce2fa7e3cfc 100644 --- a/Userland/Libraries/LibThreading/Thread.cpp +++ b/Userland/Libraries/LibThreading/Thread.cpp @@ -23,8 +23,6 @@ Thread::~Thread() dbgln("Destroying {} while it is still running undetached!", *this); [[maybe_unused]] auto res = join(); } - if (m_state == ThreadState::Detached) - dbgln("Bug! {} in state {} is being destroyed; AK/Function will crash shortly!", *this, m_state.load()); } ErrorOr Thread::set_priority(int priority) @@ -80,7 +78,8 @@ void Thread::start() // FIXME: Use pthread_attr_t to start a thread detached if that was requested by the user before the call to start(). nullptr, [](void* arg) -> void* { - Thread* self = static_cast(arg); + auto self = adopt_ref(*static_cast(arg)); + auto exit_code = self->m_action(); auto expected = Threading::ThreadState::Running; @@ -100,7 +99,7 @@ void Thread::start() return reinterpret_cast(exit_code); }, - static_cast(this)); + &NonnullRefPtr(*this).leak_ref()); VERIFY(rc == 0); #ifdef AK_OS_SERENITY diff --git a/Userland/Libraries/LibThreading/Thread.h b/Userland/Libraries/LibThreading/Thread.h index aa5f9cf7459..b3e7030fe3f 100644 --- a/Userland/Libraries/LibThreading/Thread.h +++ b/Userland/Libraries/LibThreading/Thread.h @@ -8,6 +8,7 @@ #pragma once #include +#include #include #include #include @@ -42,7 +43,7 @@ enum class ThreadState : u8 { }; class Thread final - : public RefCounted + : public AtomicRefCounted , public Weakable { public: static NonnullRefPtr construct(Function action, StringView thread_name = {})