Thread: detach

GitOrigin-RevId: 92efe8bfc3052cc9b0b75895c6a6510be8eb8fcd
This commit is contained in:
Arseny Smirnov 2018-09-11 17:55:00 +03:00
parent 5cdc7c2c53
commit c4b18325b9
2 changed files with 22 additions and 10 deletions

View File

@ -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 <class Function, class... Args>
explicit ThreadPthread(Function &&f, Args &&... args) {
func_ = std::make_unique<std::unique_ptr<Destructor>>(
create_destructor([args = std::make_tuple(decay_copy(std::forward<Function>(f)),
auto func = create_destructor([args = std::make_tuple(decay_copy(std::forward<Function>(f)),
decay_copy(std::forward<Args>(args))...)]() mutable {
invoke_tuple(std::move(args));
clear_thread_locals();
}));
pthread_create(&thread_, nullptr, run_thread, func_.get());
});
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<bool> is_inited_;
pthread_t thread_;
std::unique_ptr<std::unique_ptr<Destructor>> func_;
template <class T>
std::decay_t<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<decltype(func_.get())>(ptr);
auto func = std::unique_ptr<Destructor>(static_cast<Destructor *>(ptr));
func->reset();
return nullptr;
}

View File

@ -43,6 +43,9 @@ class ThreadStl {
void join() {
thread_.join();
}
void detach() {
thread_.detach();
}
static unsigned hardware_concurrency() {
return std::thread::hardware_concurrency();