Download src/common/threads.h from Ozomozyan/hkimi: direct link, hf CLI and curl.
- Browser
- Download file 1.45 kB
-
https://huggingface.co/Ozomozyan/hkimi/resolve/main/src/common/threads.h
- Command line
-
hf download hf://Ozomozyan/hkimi/src/common/threads.h
-
curl -L -o threads.h https://huggingface.co/Ozomozyan/hkimi/resolve/main/src/common/threads.h
1.45 kB
| // A small thread pool with a blocking parallel_for (std::thread only). | |
| 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<void(int64_t, int64_t)>& fn); | |
| // sized to the machine, HKIMI_THREADS overrides | |
| static ThreadPool& global(); | |
| private: | |
| void worker_loop(); | |
| void run_chunks(); | |
| std::vector<std::thread> 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<void(int64_t, int64_t)>* 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<void(int64_t, int64_t)>& fn) { | |
| ThreadPool::global().parallel_for(n, grain, fn); | |
| } | |
| } // namespace hk | |