Small ThreadPool improvements

This commit is contained in:
2024-03-15 22:37:02 +01:00
parent a14eb1c501
commit 0095f9ff69

View File

@@ -8,16 +8,17 @@ ThreadPool::ThreadPool(std::function<void(std::string)> onError, std::size_t wor
} }
ThreadPool::~ThreadPool() { ThreadPool::~ThreadPool() {
{
std::lock_guard lock(queueLock);
stop = true; stop = true;
somethingNew.notify_all(); somethingNew.notify_all();
}
for (auto &t: threads) { t.join(); } for (auto &t: threads) { t.join(); }
} }
void ThreadPool::push(std::function<void()> &&func) { void ThreadPool::push(std::function<void()> &&func) {
{
std::lock_guard lock(queueLock); std::lock_guard lock(queueLock);
queue.push(std::move(func)); queue.push(std::move(func));
}
somethingNew.notify_one(); somethingNew.notify_one();
} }
@@ -43,17 +44,14 @@ void ThreadPool::loop() {
queue.pop(); queue.pop();
qLock.unlock(); qLock.unlock();
try { try {
task(); task();
} catch (std::exception &e) { onError(std::string(e.what())); } } catch (std::exception &e) { onError(std::string(e.what())); }
qLock.lock();
{
std::lock_guard qLock(queueLock);
running--; running--;
if (queue.empty() && running == 0) { finished.notify_all(); } if (queue.empty() && running == 0) { finished.notify_all(); }
} }
}
} }
bool ThreadPool::empty() { bool ThreadPool::empty() {