// Bounded thread pool with a blocking parallel_for. Threads are created once (lazy singleton) and reused. #pragma once #include #include #include #include #include #include #include #include #include "raid/core/types.hpp" namespace raid { class ThreadPool { public: explicit ThreadPool(unsigned n_threads = 0); ~ThreadPool(); ThreadPool(const ThreadPool&) = delete; ThreadPool& operator=(const ThreadPool&) = delete; unsigned size() const { return static_cast(workers_.size()); } /// Runs fn(begin, end) over [0,n) split in chunks of `grain` (0 = automatic). Blocks until all chunks finished. /// Exceptions thrown by fn are rethrown on the calling thread (first one). void parallel_for(usize n, const std::function& fn, usize grain = 0); /// Global pool sized to hardware concurrency (or RAID_THREADS env var). static ThreadPool& global(); private: void worker(); std::vector workers_; std::deque> queue_; std::mutex m_; std::condition_variable cv_; bool stop_{false}; }; /// Serial fallback helper: parallel_for with n_threads==1 semantics. inline void serial_for(usize n, const std::function& fn) { if (n) fn(0, n); } } // namespace raid