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