From 41eabc72610ea5853d486a61fb2f046fdaee5cf5 Mon Sep 17 00:00:00 2001 From: Adrien Beraud <adrien.beraud@savoirfairelinux.com> Date: Sat, 25 Mar 2023 18:22:58 -0400 Subject: [PATCH] thread pool: handle exceptions starting threads --- src/thread_pool.cpp | 58 +++++++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 26 deletions(-) diff --git a/src/thread_pool.cpp b/src/thread_pool.cpp index 2daa3b93..5eb843d3 100644 --- a/src/thread_pool.cpp +++ b/src/thread_pool.cpp @@ -65,33 +65,39 @@ ThreadPool::run(std::function<void()>&& cb) // launch new thread if necessary if (not readyThreads_ && threads_.size() < maxThreads_) { - threads_.emplace_back(std::make_unique<std::thread>([this]() { - while (true) { - std::function<void()> task; - - // pick task from queue - { - std::unique_lock<std::mutex> l(lock_); - readyThreads_++; - cv_.wait(l, [&](){ - return not running_ or not tasks_.empty(); - }); - readyThreads_--; - if (not running_) - break; - task = std::move(tasks_.front()); - tasks_.pop(); - } - - // run task - try { - task(); - } catch (const std::exception& e) { - // LOG_ERR("Exception running task: %s", e.what()); - std::cerr << "Exception running task: " << e.what() << std::endl; + try { + threads_.emplace_back(std::make_unique<std::thread>([this]() { + while (true) { + std::function<void()> task; + + // pick task from queue + { + std::unique_lock<std::mutex> l(lock_); + readyThreads_++; + cv_.wait(l, [&](){ + return not running_ or not tasks_.empty(); + }); + readyThreads_--; + if (not running_) + break; + task = std::move(tasks_.front()); + tasks_.pop(); + } + + // run task + try { + task(); + } catch (const std::exception& e) { + // LOG_ERR("Exception running task: %s", e.what()); + std::cerr << "Exception running task: " << e.what() << std::endl; + } } - } - })); + })); + } catch(const std::exception& e) { + std::cerr << "Exception starting thread: " << e.what() << std::endl; + if (threads_.empty()) + throw; + } } // push task to queue -- GitLab