// A small thread pool with a blocking parallel_for (std::thread only). #pragma once #include #include #include #include #include #include #include namespace hk { class ThreadPool { public: explicit ThreadPool(int threads); ~ThreadPool(); ThreadPool(const ThreadPool&) = delete; ThreadPool& operator=(const ThreadPool&) = delete; int size() const { return (int)workers_.size() + 1; } // workers + the calling thread // fn(begin, end) over [0, n) in chunks of about `grain`. Blocks until done; the // caller works too. Nested calls run serially. void parallel_for(int64_t n, int64_t grain, const std::function& fn); // sized to the machine, HKIMI_THREADS overrides static ThreadPool& global(); private: void worker_loop(); void run_chunks(); std::vector workers_; std::mutex mu_; std::condition_variable cv_work_, cv_done_; bool stop_ = false; uint64_t generation_ = 0; // the current job, guarded by mu_ const std::function* fn_ = nullptr; int64_t n_ = 0, grain_ = 1, next_ = 0; int active_ = 0; std::exception_ptr error_; }; inline void parallel_for(int64_t n, int64_t grain, const std::function& fn) { ThreadPool::global().parallel_for(n, grain, fn); } } // namespace hk