erebus

annotate liberebus/src/threadpool.h @ 26:c8a6fb04fefa

multithreadededit
author John Tsiombikas <nuclear@member.fsf.org>
date Sun, 01 Jun 2014 19:19:40 +0300
parents 4336acf8389d
children d15ee526daa6
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@26 35 ThreadPool(int num_threads = -1);
nuclear@26 36 ~ThreadPool();
nuclear@26 37
nuclear@26 38 void add_work(std::function<void ()> func);
nuclear@26 39 void add_work(std::function<void ()> work_func, std::function<void ()> done_func);
nuclear@26 40
nuclear@26 41 // returns the number of queued work items
nuclear@26 42 int queued() const;
nuclear@26 43 // returns the number of active threads
nuclear@26 44 int active() const;
nuclear@26 45 // returns number of pending work items (both in the queue and active)
nuclear@26 46 int pending() const;
nuclear@26 47
nuclear@26 48 // waits for all work to be completed
nuclear@26 49 long wait();
nuclear@26 50 long wait(long timeout);
nuclear@26 51 };
nuclear@26 52
nuclear@26 53 #endif // THREAD_POOL_H_