From 1cbf18ff8463946aa5a09ccf1d6873b222b912b6 Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Fri, 14 Apr 2023 10:26:51 +0100 Subject: Simplify worker with jthread Moves thread collection to bottom of class so threads are joined before job storage is destroyed. --- lib/work.h | 12 ------------ lib/worker.cpp | 5 +---- lib/worker.h | 4 ++-- 3 files changed, 3 insertions(+), 18 deletions(-) delete mode 100644 lib/work.h diff --git a/lib/work.h b/lib/work.h deleted file mode 100644 index c780e13..0000000 --- a/lib/work.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -class Work { -public: - virtual ~Work() = default; - NO_COPY(Work); - NO_MOVE(Work); - - virtual void doWork() = 0; -}; diff --git a/lib/worker.cpp b/lib/worker.cpp index cf59f56..4f1352d 100644 --- a/lib/worker.cpp +++ b/lib/worker.cpp @@ -9,16 +9,13 @@ Worker Worker::instance; Worker::Worker() : todoLen {0} { std::generate_n(std::back_inserter(threads), std::thread::hardware_concurrency(), [this]() { - return std::thread {&Worker::worker, this}; + return std::jthread {&Worker::worker, this}; }); } Worker::~Worker() { todoLen.release(std::thread::hardware_concurrency()); - std::for_each(threads.begin(), threads.end(), [](auto & th) { - th.join(); - }); } void diff --git a/lib/worker.h b/lib/worker.h index 136c50e..96593d9 100644 --- a/lib/worker.h +++ b/lib/worker.h @@ -33,13 +33,13 @@ private: private: void worker(); - using Threads = std::vector; + using Threads = std::vector; using ToDo = std::deque; - Threads threads; ToDo todo; std::counting_semaphore<16> todoLen; std::mutex todoMutex; + Threads threads; static Worker instance; }; -- cgit v1.2.3