Skip to content

Commit

Permalink
LibThreading: Add new detach() API to Thread
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
SpencerCDixon authored and awesomekling committed Jul 2, 2021
1 parent 5666809 commit 48731e9
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
12 changes: 11 additions & 1 deletion Userland/Libraries/LibThreading/Thread.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Threading::Thread::Thread(Function<intptr_t()> 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();
}
Expand All @@ -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;
}
3 changes: 3 additions & 0 deletions Userland/Libraries/LibThreading/Thread.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/*
* Copyright (c) 2019-2020, Sergey Bugaev <[email protected]>
* Copyright (c) 2021, Spencer Dixon <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
Expand All @@ -24,6 +25,7 @@ class Thread final : public Core::Object {
virtual ~Thread();

void start();
void detach();

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

template<typename T>
Expand Down

0 comments on commit 48731e9

Please sign in to comment.