nuclear@26: #ifndef THREAD_POOL_H_ nuclear@26: #define THREAD_POOL_H_ nuclear@26: nuclear@26: #include nuclear@26: #include nuclear@26: #include nuclear@26: #include nuclear@26: #include nuclear@26: nuclear@26: class ThreadPool { nuclear@26: private: nuclear@26: int num_threads; nuclear@26: std::thread *thread; // array of threads nuclear@26: nuclear@26: struct WorkItem { nuclear@26: std::function work; nuclear@26: std::function done; nuclear@26: }; nuclear@26: nuclear@26: int qsize; nuclear@26: std::list workq; nuclear@26: mutable std::mutex workq_mutex; nuclear@26: std::condition_variable workq_condvar; nuclear@26: nuclear@26: int nactive; // number of active workers (not sleeping) nuclear@26: nuclear@26: // condvar used by wait nuclear@26: std::condition_variable done_condvar; nuclear@26: nuclear@26: bool quit; nuclear@26: nuclear@26: void thread_func(); nuclear@26: nuclear@26: public: nuclear@34: // passing num_threads == -1 auto-detects based on number of processors nuclear@34: explicit ThreadPool(int num_threads = -1); nuclear@26: ~ThreadPool(); nuclear@26: nuclear@26: void add_work(std::function func); nuclear@26: void add_work(std::function work_func, std::function done_func); nuclear@34: void clear_work(); nuclear@26: nuclear@26: // returns the number of queued work items nuclear@26: int queued() const; nuclear@26: // returns the number of active threads nuclear@26: int active() const; nuclear@26: // returns number of pending work items (both in the queue and active) nuclear@26: int pending() const; nuclear@26: nuclear@26: // waits for all work to be completed nuclear@26: long wait(); nuclear@26: long wait(long timeout); nuclear@26: }; nuclear@26: nuclear@26: #endif // THREAD_POOL_H_