A Hopf, Skip and a Jump
thread_pool.h
1 #ifndef _THREAD_POOL_H_
2 #define _THREAD_POOL_H_
3 
4 #include <memory>
5 #include <thread>
6 #include <mutex>
7 #include <condition_variable>
8 #include <functional>
9 #include <stdexcept>
10 
36 class ThreadPool {
37 public:
39  typedef std::function<void(void*)> delegate_t;
40 
41 protected:
43  enum state {waiting, running, dying, dead};
44 
46  std::unique_ptr<std::thread[]> workers;
47 
49  std::unique_ptr<enum state[]> states;
50 
52  std::unique_ptr<std::exception_ptr[]> exceptions;
53 
55  void** params;
56 
58  delegate_t delegate;
59 
61  std::mutex m;
66  std::condition_variable cv;
71  std::size_t remain;
79  void wait_raise(std::unique_lock<std::mutex>& lk, const std::size_t to_check);
80 
86  void dispatcher(int id);
87 
88 public:
90  const std::size_t threads;
92  ThreadPool(std::size_t numThreads = 0);
97  ~ThreadPool();
110  void manifold(delegate_t delegate,
111  void** params,
112  std::size_t jobs);
113 };
114 
115 #endif
const std::size_t threads
Number of threads in pool.
Definition: thread_pool.h:90
std::condition_variable cv
Condition variable through which to notify workers that jobs are available.
Definition: thread_pool.h:66
std::unique_ptr< enum state[]> states
State variables for each thread.
Definition: thread_pool.h:49
std::function< void(void *)> delegate_t
The type of the delegate function each thread will run.
Definition: thread_pool.h:39
std::size_t remain
Count of the number of workers still to complete their job packets.
Definition: thread_pool.h:71
void manifold(delegate_t delegate, void **params, std::size_t jobs)
Execute a function in each of the threads, passing each one its own paramater set.
~ThreadPool()
Destroy the thread pool.
std::mutex m
Mutex to control access to job packets.
Definition: thread_pool.h:61
void wait_raise(std::unique_lock< std::mutex > &lk, const std::size_t to_check)
Convenience function: waits for a lock then deals with any exceptions propagated from the threads...
A utility class to permit a single function to be run on multiple datasets concurrently.
Definition: thread_pool.h:36
void dispatcher(int id)
Dispatch jobs to the given delegate.
ThreadPool(std::size_t numThreads=0)
Construct a thread pool.
state
thread state descriptor
Definition: thread_pool.h:43
void ** params
Parameters for each thread, passed to the runJobs function.
Definition: thread_pool.h:55
delegate_t delegate
The work the workers are supposed to perform.
Definition: thread_pool.h:58
std::unique_ptr< std::thread[]> workers
Worker threads.
Definition: thread_pool.h:46
std::unique_ptr< std::exception_ptr[]> exceptions
exception_ptrs for each thread
Definition: thread_pool.h:52