This commit is contained in:
Samer Afach 2017-06-06 19:07:50 +02:00
parent 20f6a9a8fd
commit 0e45acf8ce
3 changed files with 6 additions and 7 deletions

View File

@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 2.8) cmake_minimum_required(VERSION 2.8)
project(ThreadPool) project(ThreadPool)
add_library(threadpool_lib "src/ThreadPool.cpp") add_library(threadpool_lib "include/ThreadPool.cpp")
add_executable(${PROJECT_NAME} "main.cpp") add_executable(${PROJECT_NAME} "main.cpp")

View File

@ -9,14 +9,14 @@
#include <vector> #include <vector>
class ThreadPool { class ThreadPool {
int numOfThreads; long numOfThreads;
std::deque<std::function<void()>> _tasks; std::deque<std::function<void()>> _tasks;
std::mutex _queueLock; std::mutex _queueLock;
std::atomic<bool> stopped{false}; std::atomic<bool> stopped{false};
bool startedAlready = false; bool startedAlready = false;
std::condition_variable _queueCond; std::condition_variable _queueCond;
std::condition_variable _threadFinishedCond; std::condition_variable _threadFinishedCond;
std::atomic_int numOfThreadsRunning{0}; long numOfThreadsRunning = 0;
std::vector<std::thread> _threads; std::vector<std::thread> _threads;
protected: protected:
@ -28,7 +28,7 @@ public:
inline ~ThreadPool(); inline ~ThreadPool();
inline void push(const std::function<void()> &task); inline void push(const std::function<void()> &task);
inline void inline void
start(const int NumOfThreads = std::thread::hardware_concurrency()); start(const long NumOfThreads = std::thread::hardware_concurrency());
inline void finish(); inline void finish();
}; };
@ -67,11 +67,10 @@ ThreadPool::~ThreadPool() { this->finish(); }
void ThreadPool::push(const std::function<void()> &task) { void ThreadPool::push(const std::function<void()> &task) {
std::unique_lock<decltype(_queueLock)> lg(_queueLock); std::unique_lock<decltype(_queueLock)> lg(_queueLock);
_tasks.push_back(task); _tasks.push_back(task);
lg.unlock();
_queueCond.notify_one(); _queueCond.notify_one();
} }
void ThreadPool::start(const int NumOfThreads) { void ThreadPool::start(const long NumOfThreads) {
if (!startedAlready) if (!startedAlready)
startedAlready = true; startedAlready = true;
else else

View File

@ -1,6 +1,6 @@
#include <iostream> #include <iostream>
#include "src/ThreadPool.h" #include "include/ThreadPool.h"
void SumZeroToNumber(long &num) { void SumZeroToNumber(long &num) {
long val = 0; long val = 0;