From e9aaed4aea9e2a5d38529706a47f97e33b90ce2c Mon Sep 17 00:00:00 2001 From: qicosmos Date: Tue, 11 Jul 2023 14:49:55 +0800 Subject: [PATCH 1/2] free pool when destructing --- include/ylt/coro_io/io_context_pool.hpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/include/ylt/coro_io/io_context_pool.hpp b/include/ylt/coro_io/io_context_pool.hpp index 79755bb53..256de89a3 100644 --- a/include/ylt/coro_io/io_context_pool.hpp +++ b/include/ylt/coro_io/io_context_pool.hpp @@ -127,10 +127,10 @@ class io_context_pool { return; } - // ~io_context_pool() { - // if (!has_stop()) - // stop(); - // } + ~io_context_pool() { + if (!has_stop()) + stop(); + } std::size_t pool_size() const noexcept { return io_contexts_.size(); } From c6a3e6a979221f6060c9cd2263ccd2f7aa5353d1 Mon Sep 17 00:00:00 2001 From: qicosmos Date: Tue, 11 Jul 2023 16:03:37 +0800 Subject: [PATCH 2/2] fix --- include/ylt/coro_io/io_context_pool.hpp | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/include/ylt/coro_io/io_context_pool.hpp b/include/ylt/coro_io/io_context_pool.hpp index 256de89a3..8431dc0ab 100644 --- a/include/ylt/coro_io/io_context_pool.hpp +++ b/include/ylt/coro_io/io_context_pool.hpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -106,6 +107,12 @@ class io_context_pool { } void run() { + bool has_run_or_stop = false; + bool ok = has_run_or_stop_.compare_exchange_strong(has_run_or_stop, true); + if (!ok) { + return; + } + std::vector> threads; for (std::size_t i = 0; i < io_contexts_.size(); ++i) { threads.emplace_back(std::make_shared( @@ -122,9 +129,18 @@ class io_context_pool { } void stop() { - work_.clear(); - promise_.get_future().wait(); - return; + std::call_once(flag_, [this] { + bool has_run_or_stop = false; + bool ok = has_run_or_stop_.compare_exchange_strong(has_run_or_stop, true); + + work_.clear(); + + if (ok) { + return; + } + + promise_.get_future().wait(); + }); } ~io_context_pool() { @@ -156,6 +172,8 @@ class io_context_pool { std::vector work_; std::atomic next_io_context_; std::promise promise_; + std::atomic has_run_or_stop_ = false; + std::once_flag flag_; }; class multithread_context_pool {