浏览代码

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.
Spencer Dixon 4 年之前
父节点
当前提交
48731e9f17
共有 2 个文件被更改,包括 14 次插入1 次删除
  1. 11 1
      Userland/Libraries/LibThreading/Thread.cpp
  2. 3 0
      Userland/Libraries/LibThreading/Thread.h

+ 11 - 1
Userland/Libraries/LibThreading/Thread.cpp

@@ -20,7 +20,7 @@ Threading::Thread::Thread(Function<intptr_t()> action, StringView thread_name)
 
 
 Threading::Thread::~Thread()
 Threading::Thread::~Thread()
 {
 {
-    if (m_tid) {
+    if (m_tid && !m_detached) {
         dbgln("Destroying thread \"{}\"({}) while it is still running!", m_thread_name, m_tid);
         dbgln("Destroying thread \"{}\"({}) while it is still running!", m_thread_name, m_tid);
         [[maybe_unused]] auto res = join();
         [[maybe_unused]] auto res = join();
     }
     }
@@ -46,3 +46,13 @@ void Threading::Thread::start()
     }
     }
     dbgln("Started thread \"{}\", tid = {}", m_thread_name, m_tid);
     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 - 0
Userland/Libraries/LibThreading/Thread.h

@@ -1,5 +1,6 @@
 /*
 /*
  * Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
  * Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
+ * Copyright (c) 2021, Spencer Dixon <spencercdixon@gmail.com>
  *
  *
  * SPDX-License-Identifier: BSD-2-Clause
  * SPDX-License-Identifier: BSD-2-Clause
  */
  */
@@ -24,6 +25,7 @@ public:
     virtual ~Thread();
     virtual ~Thread();
 
 
     void start();
     void start();
+    void detach();
 
 
     template<typename T = void>
     template<typename T = void>
     Result<T, ThreadError> join();
     Result<T, ThreadError> join();
@@ -36,6 +38,7 @@ private:
     Function<intptr_t()> m_action;
     Function<intptr_t()> m_action;
     pthread_t m_tid { 0 };
     pthread_t m_tid { 0 };
     String m_thread_name;
     String m_thread_name;
+    bool m_detached { false };
 };
 };
 
 
 template<typename T>
 template<typename T>