Skip to content
Snippets Groups Projects
Commit 41eabc72 authored by Adrien Béraud's avatar Adrien Béraud
Browse files

thread pool: handle exceptions starting threads

parent 424fe61a
No related branches found
No related tags found
Loading
...@@ -65,33 +65,39 @@ ThreadPool::run(std::function<void()>&& cb) ...@@ -65,33 +65,39 @@ ThreadPool::run(std::function<void()>&& cb)
// launch new thread if necessary // launch new thread if necessary
if (not readyThreads_ && threads_.size() < maxThreads_) { if (not readyThreads_ && threads_.size() < maxThreads_) {
threads_.emplace_back(std::make_unique<std::thread>([this]() { try {
while (true) { threads_.emplace_back(std::make_unique<std::thread>([this]() {
std::function<void()> task; while (true) {
std::function<void()> task;
// pick task from queue
{ // pick task from queue
std::unique_lock<std::mutex> l(lock_); {
readyThreads_++; std::unique_lock<std::mutex> l(lock_);
cv_.wait(l, [&](){ readyThreads_++;
return not running_ or not tasks_.empty(); cv_.wait(l, [&](){
}); return not running_ or not tasks_.empty();
readyThreads_--; });
if (not running_) readyThreads_--;
break; if (not running_)
task = std::move(tasks_.front()); break;
tasks_.pop(); task = std::move(tasks_.front());
} tasks_.pop();
}
// run task
try { // run task
task(); try {
} catch (const std::exception& e) { task();
// LOG_ERR("Exception running task: %s", e.what()); } catch (const std::exception& e) {
std::cerr << "Exception running task: " << e.what() << std::endl; // 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 // push task to queue
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment