Skip to content

Commit 48731e9

Browse files
SpencerCDixonawesomekling
authored andcommitted
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.
1 parent 5666809 commit 48731e9

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

Userland/Libraries/LibThreading/Thread.cpp

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ Threading::Thread::Thread(Function<intptr_t()> action, StringView thread_name)
2020

2121
Threading::Thread::~Thread()
2222
{
23-
if (m_tid) {
23+
if (m_tid && !m_detached) {
2424
dbgln("Destroying thread \"{}\"({}) while it is still running!", m_thread_name, m_tid);
2525
[[maybe_unused]] auto res = join();
2626
}
@@ -46,3 +46,13 @@ void Threading::Thread::start()
4646
}
4747
dbgln("Started thread \"{}\", tid = {}", m_thread_name, m_tid);
4848
}
49+
50+
void Threading::Thread::detach()
51+
{
52+
VERIFY(!m_detached);
53+
54+
int rc = pthread_detach(m_tid);
55+
VERIFY(rc == 0);
56+
57+
m_detached = true;
58+
}

Userland/Libraries/LibThreading/Thread.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/*
22
* Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
3+
* Copyright (c) 2021, Spencer Dixon <spencercdixon@gmail.com>
34
*
45
* SPDX-License-Identifier: BSD-2-Clause
56
*/
@@ -24,6 +25,7 @@ class Thread final : public Core::Object {
2425
virtual ~Thread();
2526

2627
void start();
28+
void detach();
2729

2830
template<typename T = void>
2931
Result<T, ThreadError> join();
@@ -36,6 +38,7 @@ class Thread final : public Core::Object {
3638
Function<intptr_t()> m_action;
3739
pthread_t m_tid { 0 };
3840
String m_thread_name;
41+
bool m_detached { false };
3942
};
4043

4144
template<typename T>

0 commit comments

Comments
 (0)