From c4b18325b985619d17a9bcedcc468099f48b9e21 Mon Sep 17 00:00:00 2001 From: Arseny Smirnov Date: Tue, 11 Sep 2018 17:55:00 +0300 Subject: [PATCH] Thread: detach GitOrigin-RevId: 92efe8bfc3052cc9b0b75895c6a6510be8eb8fcd --- tdutils/td/utils/port/detail/ThreadPthread.h | 29 +++++++++++++------- tdutils/td/utils/port/detail/ThreadStl.h | 3 ++ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/tdutils/td/utils/port/detail/ThreadPthread.h b/tdutils/td/utils/port/detail/ThreadPthread.h index 11199dca..fc23efd5 100644 --- a/tdutils/td/utils/port/detail/ThreadPthread.h +++ b/tdutils/td/utils/port/detail/ThreadPthread.h @@ -32,16 +32,19 @@ class ThreadPthread { ThreadPthread(const ThreadPthread &other) = delete; ThreadPthread &operator=(const ThreadPthread &other) = delete; ThreadPthread(ThreadPthread &&) = default; - ThreadPthread &operator=(ThreadPthread &&) = default; + ThreadPthread &operator=(ThreadPthread &&other) { + join(); + is_inited_ = std::move(other.is_inited_); + thread_ = other.thread_; + } template explicit ThreadPthread(Function &&f, Args &&... args) { - func_ = std::make_unique>( - create_destructor([args = std::make_tuple(decay_copy(std::forward(f)), - decay_copy(std::forward(args))...)]() mutable { - invoke_tuple(std::move(args)); - clear_thread_locals(); - })); - pthread_create(&thread_, nullptr, run_thread, func_.get()); + auto func = create_destructor([args = std::make_tuple(decay_copy(std::forward(f)), + decay_copy(std::forward(args))...)]() mutable { + invoke_tuple(std::move(args)); + clear_thread_locals(); + }); + pthread_create(&thread_, nullptr, run_thread, func.release()); is_inited_ = true; } void join() { @@ -50,6 +53,13 @@ class ThreadPthread { pthread_join(thread_, nullptr); } } + + void detach() { + if (is_inited_.get()) { + is_inited_ = false; + pthread_detach(thread_); + } + } ~ThreadPthread() { join(); } @@ -63,7 +73,6 @@ class ThreadPthread { private: MovableValue is_inited_; pthread_t thread_; - std::unique_ptr> func_; template std::decay_t decay_copy(T &&v) { @@ -72,7 +81,7 @@ class ThreadPthread { static void *run_thread(void *ptr) { ThreadIdGuard thread_id_guard; - auto func = static_cast(ptr); + auto func = std::unique_ptr(static_cast(ptr)); func->reset(); return nullptr; } diff --git a/tdutils/td/utils/port/detail/ThreadStl.h b/tdutils/td/utils/port/detail/ThreadStl.h index 91e0b98e..4222233f 100644 --- a/tdutils/td/utils/port/detail/ThreadStl.h +++ b/tdutils/td/utils/port/detail/ThreadStl.h @@ -43,6 +43,9 @@ class ThreadStl { void join() { thread_.join(); } + void detach() { + thread_.detach(); + } static unsigned hardware_concurrency() { return std::thread::hardware_concurrency();