distray
diff src/threadpool.h @ 0:cf494adee646
distance field raytracer
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Fri, 25 Dec 2015 05:41:10 +0200 |
parents | |
children |
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/src/threadpool.h Fri Dec 25 05:41:10 2015 +0200 1.3 @@ -0,0 +1,55 @@ 1.4 +#ifndef THREAD_POOL_H_ 1.5 +#define THREAD_POOL_H_ 1.6 + 1.7 +#include <list> 1.8 +#include <functional> 1.9 +#include <thread> 1.10 +#include <mutex> 1.11 +#include <condition_variable> 1.12 + 1.13 +class ThreadPool { 1.14 +private: 1.15 + int num_threads; 1.16 + std::thread *thread; // array of threads 1.17 + 1.18 + struct WorkItem { 1.19 + std::function<void ()> work; 1.20 + std::function<void ()> done; 1.21 + }; 1.22 + 1.23 + int qsize; 1.24 + std::list<WorkItem> workq; 1.25 + mutable std::mutex workq_mutex; 1.26 + std::condition_variable workq_condvar; 1.27 + 1.28 + int nactive; // number of active workers (not sleeping) 1.29 + 1.30 + // condvar used by wait 1.31 + std::condition_variable done_condvar; 1.32 + 1.33 + bool quit; 1.34 + 1.35 + void thread_func(); 1.36 + 1.37 +public: 1.38 + // passing num_threads == -1 auto-detects based on number of processors 1.39 + explicit ThreadPool(int num_threads = -1); 1.40 + ~ThreadPool(); 1.41 + 1.42 + void add_work(std::function<void ()> func); 1.43 + void add_work(std::function<void ()> work_func, std::function<void ()> done_func); 1.44 + void clear_work(); 1.45 + 1.46 + // returns the number of queued work items 1.47 + int queued() const; 1.48 + // returns the number of active threads 1.49 + int active() const; 1.50 + // returns number of pending work items (both in the queue and active) 1.51 + int pending() const; 1.52 + 1.53 + // waits for all work to be completed 1.54 + long wait(); 1.55 + long wait(long timeout); 1.56 +}; 1.57 + 1.58 +#endif // THREAD_POOL_H_