hkimi / src /common /threads.h
Ozomozyan's picture
hkimi 0.1.0
68888be verified
Raw History Blame Contribute Delete
1.45 kB
// A small thread pool with a blocking parallel_for (std::thread only).
#pragma once
#include <condition_variable>
#include <cstdint>
#include <exception>
#include <functional>
#include <mutex>
#include <thread>
#include <vector>
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