#include "common/threads.h" #include #include #include namespace hk { static thread_local bool tl_in_pool = false; ThreadPool::ThreadPool(int threads) { int n = std::max(1, threads) - 1; workers_.reserve((size_t)n); for (int i = 0; i < n; ++i) workers_.emplace_back([this] { worker_loop(); }); } ThreadPool::~ThreadPool() { { std::lock_guard lock(mu_); stop_ = true; } cv_work_.notify_all(); for (auto& t : workers_) t.join(); } void ThreadPool::run_chunks() { // called with mu_ unlocked while (true) { int64_t b, e; const std::function* fn; { std::lock_guard lock(mu_); if (fn_ == nullptr || next_ >= n_) return; b = next_; e = std::min(n_, b + grain_); next_ = e; fn = fn_; ++active_; } // keep the first exception and rethrow it on the calling thread std::exception_ptr err; try { (*fn)(b, e); } catch (...) { err = std::current_exception(); } { std::lock_guard lock(mu_); if (err) { if (!error_) error_ = err; next_ = n_; // stop handing out chunks } --active_; if (next_ >= n_ && active_ == 0) cv_done_.notify_all(); } } } void ThreadPool::worker_loop() { tl_in_pool = true; uint64_t seen = 0; while (true) { { std::unique_lock lock(mu_); cv_work_.wait(lock, [&] { return stop_ || generation_ != seen; }); if (stop_) return; seen = generation_; } run_chunks(); } } void ThreadPool::parallel_for(int64_t n, int64_t grain, const std::function& fn) { if (n <= 0) return; grain = std::max(1, grain); // small job, pool of one, or nested call if (workers_.empty() || n <= grain || tl_in_pool) { fn(0, n); return; } { std::lock_guard lock(mu_); fn_ = &fn; n_ = n; grain_ = grain; next_ = 0; active_ = 0; error_ = nullptr; ++generation_; } cv_work_.notify_all(); tl_in_pool = true; // the caller participates; nested parallel_for inside fn stays serial run_chunks(); tl_in_pool = false; std::unique_lock lock(mu_); cv_done_.wait(lock, [&] { return next_ >= n_ && active_ == 0; }); fn_ = nullptr; if (error_) { std::exception_ptr err = error_; error_ = nullptr; lock.unlock(); std::rethrow_exception(err); } } ThreadPool& ThreadPool::global() { static ThreadPool pool([] { int n = (int)std::thread::hardware_concurrency(); if (const char* env = std::getenv("HKIMI_THREADS")) n = std::atoi(env); return std::max(1, n); }()); return pool; } } // namespace hk