#ifndef THREAD_POOL_H #define THREAD_POOL_H #include #include #include #include #include #include class ThreadPool; // our worker thread objects class Worker { public: Worker(ThreadPool &s) : pool(s) { } void operator()(); private: ThreadPool &pool; }; template class Result { struct ResultImpl { ResultImpl() : value(T()), available(false) { } T value; bool available; std::mutex lock; std::condition_variable cond; }; public: Result() : impl(new ResultImpl()) { } bool available() const { std::unique_lock ul(impl->lock); return impl->available; } void wait() { if(!impl) return; std::unique_lock ul(impl->lock); if(impl->available) return; impl->cond.wait(ul); } void signal() const { std::unique_lock ul(impl->lock); impl->available = true; impl->cond.notify_all(); } bool valid() const { std::unique_lock ul(impl->lock); return static_cast(impl); } T& get() { wait(); return impl->value; } void set(T v) const { std::unique_lock ul(impl->lock); impl->value = v; } private: std::shared_ptr impl; }; template<> class Result { struct ResultImpl { ResultImpl() : available(false) { } bool available; std::mutex lock; std::condition_variable cond; }; public: Result() : impl(new ResultImpl()) { } bool available() const { std::unique_lock ul(impl->lock); return impl->available; } void wait() { if(!impl) return; std::unique_lock ul(impl->lock); if(impl->available) return; impl->cond.wait(ul); } void signal() const { std::unique_lock ul(impl->lock); impl->available = true; impl->cond.notify_all(); } bool valid() const { std::unique_lock ul(impl->lock); return static_cast(impl); } private: std::shared_ptr impl; }; // the actual thread pool class ThreadPool { public: ThreadPool(size_t); template Result enqueue(F f); ~ThreadPool(); private: friend class Worker; // need to keep track of threads so we can join them std::vector< std::thread > workers; // the task queue std::deque< std::function > tasks; // synchronization std::mutex queue_mutex; std::condition_variable condition; bool stop; }; void Worker::operator()() { std::function task; while(true) { { std::unique_lock lock(pool.queue_mutex); while(!pool.stop && pool.tasks.empty()) pool.condition.wait(lock); if(pool.stop) return; task = pool.tasks.front(); pool.tasks.pop_front(); } task(); } } // the constructor just launches some amount of workers ThreadPool::ThreadPool(size_t threads) : stop(false) { for(size_t i = 0;i struct CallAndSet { void operator()(const Result &res, const F f) { res.set(f()); res.signal(); } }; template struct CallAndSet { void operator()(const Result &res, const F &f) { f(); res.signal(); } }; // add new work item to the pool template Result ThreadPool::enqueue(F f) { Result res; { std::unique_lock lock(queue_mutex); tasks.push_back(std::function( [f,res]() { CallAndSet()(res, f); })); } condition.notify_one(); return res; } // the destructor joins all threads ThreadPool::~ThreadPool() { stop = true; condition.notify_all(); for(size_t i = 0;i