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