From 375d5a38b1aafa98edf306fbdc6f9eb601a4ddd5 Mon Sep 17 00:00:00 2001 From: Samer Afach Date: Tue, 6 Jun 2017 19:31:23 +0200 Subject: [PATCH] Removed atomicity (not necessary) and renamed some variables. --- include/ThreadPool.h | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/include/ThreadPool.h b/include/ThreadPool.h index d4365aa..d8b73fb 100644 --- a/include/ThreadPool.h +++ b/include/ThreadPool.h @@ -1,7 +1,6 @@ #ifndef THREADPOOL_H #define THREADPOOL_H -#include #include #include #include @@ -12,16 +11,16 @@ class ThreadPool { long numOfThreads; std::deque> _tasks; std::mutex _queueLock; - std::atomic stopped{false}; - bool startedAlready = false; + bool conclude_work = false; + bool started_already = false; std::condition_variable _queueCond; std::condition_variable _threadFinishedCond; - long numOfThreadsRunning = 0; + long num_of_threads_running = 0; std::vector _threads; protected: - inline void threadWorker(); - inline void joinAll(); + inline void thread_worker(); + inline void join_all(); public: inline ThreadPool(); @@ -32,10 +31,10 @@ public: inline void finish(); }; -void ThreadPool::threadWorker() { +void ThreadPool::thread_worker() { while (true) { std::unique_lock lg(_queueLock); - while (_tasks.empty() && !stopped.load()) { + while (_tasks.empty() && !conclude_work) { _queueCond.wait(lg); } if (!_tasks.empty()) { @@ -45,15 +44,15 @@ void ThreadPool::threadWorker() { theTask(); lg.lock(); } - if (_tasks.empty() && stopped.load()) { - numOfThreadsRunning--; + if (_tasks.empty() && conclude_work) { + num_of_threads_running--; _threadFinishedCond.notify_one(); break; } } } -void ThreadPool::joinAll() { +void ThreadPool::join_all() { for (long i = 0; i < numOfThreads; i++) { if (_threads[i].joinable()) _threads[i].join(); @@ -71,27 +70,28 @@ void ThreadPool::push(const std::function &task) { } void ThreadPool::start(const long NumOfThreads) { - if (!startedAlready) - startedAlready = true; + if (!started_already) + started_already = true; else throw std::logic_error("You cannot start the thread pool multiple times."); numOfThreads = NumOfThreads; _threads.reserve(numOfThreads); for (long i = 0; i < numOfThreads; i++) { - _threads.push_back(std::thread(std::bind(&ThreadPool::threadWorker, this))); - numOfThreadsRunning++; + _threads.push_back( + std::thread(std::bind(&ThreadPool::thread_worker, this))); + num_of_threads_running++; } } void ThreadPool::finish() { std::unique_lock lg(_queueLock); - stopped.store(true); + conclude_work = true; _queueCond.notify_all(); - while (numOfThreadsRunning > 0) { + while (num_of_threads_running > 0) { _threadFinishedCond.wait(lg); } lg.unlock(); - joinAll(); + join_all(); } #endif // THREADPOOL_H