From e50a81abf73ab5020a281cf17e96aad8b43c43f8 Mon Sep 17 00:00:00 2001 From: Gabriele Date: Fri, 21 Mar 2025 15:56:09 +0100 Subject: [PATCH] LibThreading: Add possibility to set threads detached before start --- Libraries/LibThreading/Thread.cpp | 17 +++++++++++++---- Libraries/LibThreading/Thread.h | 3 +++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/Libraries/LibThreading/Thread.cpp b/Libraries/LibThreading/Thread.cpp index 328a2b36add..43c154fd966 100644 --- a/Libraries/LibThreading/Thread.cpp +++ b/Libraries/LibThreading/Thread.cpp @@ -43,6 +43,11 @@ ErrorOr Thread::get_priority() const return scheduling_parameters.sched_priority; } +void Thread::set_detached_on_start() +{ + m_attribute_detached_flag = true; +} + ByteString Thread::thread_name() const { return m_thread_name; } pthread_t Thread::tid() const { return m_tid; } @@ -68,18 +73,21 @@ void Thread::start() VERIFY(!is_started()); // Set this first so that the other thread starts out seeing m_state == Running. - m_state = Threading::ThreadState::Running; - + m_state = m_attribute_detached_flag ? Threading::ThreadState::Detached : Threading::ThreadState::Running; + pthread_attr_init(&m_attribute); + if (m_attribute_detached_flag) { + pthread_attr_setdetachstate(&m_attribute, PTHREAD_CREATE_DETACHED); + } int rc = pthread_create( &m_tid, - // FIXME: Use pthread_attr_t to start a thread detached if that was requested by the user before the call to start(). - nullptr, + &m_attribute, [](void* arg) -> void* { auto self = adopt_ref(*static_cast(arg)); auto exit_code = self->m_action(); auto expected = Threading::ThreadState::Running; + // This code might race with a call to detach(). if (!self->m_state.compare_exchange_strong(expected, Threading::ThreadState::Exited)) { // If the original state was Detached, we need to set to DetachedExited instead. @@ -97,6 +105,7 @@ void Thread::start() return reinterpret_cast(exit_code); }, &NonnullRefPtr(*this).leak_ref()); + pthread_attr_destroy(&m_attribute); VERIFY(rc == 0); } diff --git a/Libraries/LibThreading/Thread.h b/Libraries/LibThreading/Thread.h index c0a9a0a0af7..08bb5dd090e 100644 --- a/Libraries/LibThreading/Thread.h +++ b/Libraries/LibThreading/Thread.h @@ -60,6 +60,7 @@ public: ErrorOr set_priority(int priority); ErrorOr get_priority() const; + void set_detached_on_start(); // Only callable in the Startable state. void start(); // Only callable in the Running state. @@ -80,6 +81,8 @@ private: explicit Thread(ESCAPING Function action, StringView thread_name = {}); Function m_action; pthread_t m_tid {}; + pthread_attr_t m_attribute; + bool m_attribute_detached_flag = { false }; ByteString m_thread_name; Atomic m_state { ThreadState::Startable }; };