From 48731e9f17262073b5f99ba113893519af2f938d Mon Sep 17 00:00:00 2001 From: Spencer Dixon Date: Fri, 2 Jul 2021 08:05:07 -0400 Subject: [PATCH] LibThreading: Add new detach() API to Thread Sometimes you don't care about `joining()` the result of a thread. The underlying pthread implementation already existed for detaching and now we expose it to the higher level API. --- Userland/Libraries/LibThreading/Thread.cpp | 12 +++++++++++- Userland/Libraries/LibThreading/Thread.h | 3 +++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/Userland/Libraries/LibThreading/Thread.cpp b/Userland/Libraries/LibThreading/Thread.cpp index 71c6c4f45e..2d0da5c118 100644 --- a/Userland/Libraries/LibThreading/Thread.cpp +++ b/Userland/Libraries/LibThreading/Thread.cpp @@ -20,7 +20,7 @@ Threading::Thread::Thread(Function action, StringView thread_name) Threading::Thread::~Thread() { - if (m_tid) { + if (m_tid && !m_detached) { dbgln("Destroying thread \"{}\"({}) while it is still running!", m_thread_name, m_tid); [[maybe_unused]] auto res = join(); } @@ -46,3 +46,13 @@ void Threading::Thread::start() } dbgln("Started thread \"{}\", tid = {}", m_thread_name, m_tid); } + +void Threading::Thread::detach() +{ + VERIFY(!m_detached); + + int rc = pthread_detach(m_tid); + VERIFY(rc == 0); + + m_detached = true; +} diff --git a/Userland/Libraries/LibThreading/Thread.h b/Userland/Libraries/LibThreading/Thread.h index d04fba6a54..ab9c18b365 100644 --- a/Userland/Libraries/LibThreading/Thread.h +++ b/Userland/Libraries/LibThreading/Thread.h @@ -1,5 +1,6 @@ /* * Copyright (c) 2019-2020, Sergey Bugaev + * Copyright (c) 2021, Spencer Dixon * * SPDX-License-Identifier: BSD-2-Clause */ @@ -24,6 +25,7 @@ public: virtual ~Thread(); void start(); + void detach(); template Result join(); @@ -36,6 +38,7 @@ private: Function m_action; pthread_t m_tid { 0 }; String m_thread_name; + bool m_detached { false }; }; template