distray

annotate 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
rev   line source
nuclear@0 1 #ifndef THREAD_POOL_H_
nuclear@0 2 #define THREAD_POOL_H_
nuclear@0 3
nuclear@0 4 #include <list>
nuclear@0 5 #include <functional>
nuclear@0 6 #include <thread>
nuclear@0 7 #include <mutex>
nuclear@0 8 #include <condition_variable>
nuclear@0 9
nuclear@0 10 class ThreadPool {
nuclear@0 11 private:
nuclear@0 12 int num_threads;
nuclear@0 13 std::thread *thread; // array of threads
nuclear@0 14
nuclear@0 15 struct WorkItem {
nuclear@0 16 std::function<void ()> work;
nuclear@0 17 std::function<void ()> done;
nuclear@0 18 };
nuclear@0 19
nuclear@0 20 int qsize;
nuclear@0 21 std::list<WorkItem> workq;
nuclear@0 22 mutable std::mutex workq_mutex;
nuclear@0 23 std::condition_variable workq_condvar;
nuclear@0 24
nuclear@0 25 int nactive; // number of active workers (not sleeping)
nuclear@0 26
nuclear@0 27 // condvar used by wait
nuclear@0 28 std::condition_variable done_condvar;
nuclear@0 29
nuclear@0 30 bool quit;
nuclear@0 31
nuclear@0 32 void thread_func();
nuclear@0 33
nuclear@0 34 public:
nuclear@0 35 // passing num_threads == -1 auto-detects based on number of processors
nuclear@0 36 explicit ThreadPool(int num_threads = -1);
nuclear@0 37 ~ThreadPool();
nuclear@0 38
nuclear@0 39 void add_work(std::function<void ()> func);
nuclear@0 40 void add_work(std::function<void ()> work_func, std::function<void ()> done_func);
nuclear@0 41 void clear_work();
nuclear@0 42
nuclear@0 43 // returns the number of queued work items
nuclear@0 44 int queued() const;
nuclear@0 45 // returns the number of active threads
nuclear@0 46 int active() const;
nuclear@0 47 // returns number of pending work items (both in the queue and active)
nuclear@0 48 int pending() const;
nuclear@0 49
nuclear@0 50 // waits for all work to be completed
nuclear@0 51 long wait();
nuclear@0 52 long wait(long timeout);
nuclear@0 53 };
nuclear@0 54
nuclear@0 55 #endif // THREAD_POOL_H_