From 0a8d717388da3d88dd7f6c5646dac347fae2b103 Mon Sep 17 00:00:00 2001 From: Andrei Lobov Date: Wed, 22 Nov 2023 01:21:53 +0100 Subject: [PATCH] Start function (#577) * Start function * wip * fix --- core/utils/async_utils.cpp | 16 +++++++++++----- core/utils/async_utils.hpp | 3 ++- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/core/utils/async_utils.cpp b/core/utils/async_utils.cpp index 60086a44f..9c1bed9b7 100644 --- a/core/utils/async_utils.cpp +++ b/core/utils/async_utils.cpp @@ -55,13 +55,19 @@ void busywait_mutex::unlock() noexcept { } template -ThreadPool::ThreadPool(size_t threads, basic_string_view name) - : name_{name} { +ThreadPool::ThreadPool(size_t threads, basic_string_view name) { + start(threads, name); +} + +template +void ThreadPool::start(size_t threads, basic_string_view name) { + IRS_ASSERT(threads_.empty()); threads_.reserve(threads); for (size_t i = 0; i != threads; ++i) { - threads_.emplace_back([&] { - if (!name_.empty()) { - set_thread_name(name_.c_str()); + threads_.emplace_back([this, name] { + if (!name.empty()) { + IRS_ASSERT(std::char_traits::length(name.data()) == name.size()); + set_thread_name(name.data()); } Work(); }); diff --git a/core/utils/async_utils.hpp b/core/utils/async_utils.hpp index 2d80a66d3..2e356ccb0 100644 --- a/core/utils/async_utils.hpp +++ b/core/utils/async_utils.hpp @@ -57,9 +57,11 @@ class ThreadPool { using Clock = std::chrono::steady_clock; using Func = fu2::unique_function; + ThreadPool() = default; explicit ThreadPool(size_t threads, basic_string_view name = {}); ~ThreadPool() { stop(true); } + void start(size_t threads, basic_string_view name = {}); bool run(Func&& fn, Clock::duration delay = {}); void stop(bool skip_pending = false) noexcept; // always a blocking call size_t tasks_active() const { @@ -95,7 +97,6 @@ class ThreadPool { bool WasStop() const { return state_ % 2 != 0; } - basic_string name_; std::vector threads_; mutable std::mutex m_; std::condition_variable cv_;