25#ifndef __JOIN_THREADPOOL_HPP__
26#define __JOIN_THREADPOOL_HPP__
85 ThreadPool (
int workers = std::max (
int (std::thread::hardware_concurrency ()), 1));
95 template <
class Function,
class... Args>
96 void push (Function&& func, Args&&... args)
98 ScopedLock <Mutex> lock (_mutex);
99 _jobs.emplace_back (std::bind (std::forward <Function> (func), std::forward <Args> (args)...));
110 std::vector <std::unique_ptr <WorkerThread>> _workers;
119 std::atomic <bool> _stop;
122 std::deque <std::function <void ()>> _jobs;
134 template <
class InputIt,
class Func>
138 int count = std::distance (first, last);
142 int concurrency = std::max (
int (std::thread::hardware_concurrency ()), 1);
144 concurrency = std::min (concurrency, count);
145 int elements = count / concurrency;
146 int rest = count % concurrency;
148 std::vector <int> tasks (concurrency, elements);
149 for (
int i = 0; i < rest; ++i)
155 std::vector <Thread> pool;
156 int nth = concurrency - 1;
160 auto beg = first, end = first;
161 for (
int i = 0; i < nth; ++i)
163 std::advance (end, tasks[i]);
164 pool.emplace_back (function, beg, end);
169 function (beg, last);
172 for (
auto& thread : pool)
185 template <
class InputIt,
class Func>
188 distribute (first, last, [&function] (InputIt beg, InputIt end)
190 for (; beg != end; ++beg)
condition variable class.
Definition condition.hpp:42
void signal() noexcept
unblocks one of the waiting threads.
Definition condition.cpp:60
class used to protect shared data from being simultaneously accessed by multiple threads.
Definition mutex.hpp:37
thread pool class.
Definition threadpool.hpp:79
~ThreadPool()
destroy thread pool.
Definition threadpool.cpp:90
ThreadPool(int workers=std::max(int(std::thread::hardware_concurrency()), 1))
create thread pool.
Definition threadpool.cpp:77
size_t size()
return thread pool size.
Definition threadpool.cpp:101
void push(Function &&func, Args &&... args)
push a job to the work queue.
Definition threadpool.hpp:96
thread class.
Definition thread.hpp:138
worker thread class.
Definition threadpool.hpp:49
~WorkerThread()
destroy worker thread.
Definition threadpool.cpp:45
WorkerThread(ThreadPool &pool)
create worker thread.
Definition threadpool.cpp:35
Definition acceptor.hpp:32
void distribute(InputIt first, InputIt last, Func function)
determine the number of threads and tasks per thread to run and execute them in parallel.
Definition threadpool.hpp:135
void parallelForEach(InputIt first, InputIt last, Func function)
parrallel for each loop.
Definition threadpool.hpp:186