18 : threads_(num_threads),
19 init_thread_(
std::move(init_thread)) {
21 for (
size_t i = 0; i < num_threads; ++i)
26 std::unique_lock<std::mutex> lock(
mutex_);
33 for (
size_t i = 0; i <
threads_.size(); ++i)
38 std::unique_lock<std::mutex> lock(
mutex_);
39 jobs_.emplace_back(std::move(job));
44 std::unique_lock<std::mutex> lock(
mutex_);
46 std::atomic_thread_fence(std::memory_order_seq_cst);
50 std::unique_lock<std::mutex> lock(
mutex_);
52 std::atomic_thread_fence(std::memory_order_seq_cst);
56 std::unique_lock<std::mutex> lock(
mutex_);
78 return (
idle_.load(std::memory_order_relaxed) != 0);
91 std::unique_lock<std::mutex> lock(
mutex_);
105 if (!
jobs_.empty()) {
121 catch (std::exception& e) {
122 std::cerr <<
"EXCEPTION: " << e.what() << std::endl;
128 std::atomic_thread_fence(std::memory_order_seq_cst);
std::atomic< size_t > done_
Counter for total number of jobs executed.
std::deque< Job > jobs_
Deque of scheduled jobs.
simple_vector< std::thread > threads_
threads in pool
size_t done() const
Return number of jobs currently completed.
size_t size() const
Return number of threads in pool.
std::atomic< bool > terminate_
Flag whether to terminate.
std::condition_variable cv_jobs_
void worker(size_t p)
Worker function, one per thread is started.
~ThreadPool()
Stop processing jobs, terminate threads.
ThreadPool(size_t num_threads=std::thread::hardware_concurrency(), InitThread &&init_thread=InitThread())
Construct running thread pool of num_threads.
void enqueue(Job &&job)
enqueue a Job, the caller must pass in all context using captures.
std::thread & thread(size_t i)
Return thread handle to thread i.
bool has_idle() const
true if any thread is idle (= waiting for jobs)
std::atomic< size_t > busy_
Counter for number of threads busy.
std::atomic< size_t > idle_
Counter for number of idle threads waiting for a job.
std::string join(char glue, const std::vector< std::string > &parts)
Join a vector of strings by some glue character between each pair from the sequence.
std::condition_variable cv_finished_
Condition variable to signal when a jobs finishes.
void loop_until_terminate()
Loop until terminate flag was set.
size_t idle() const
return number of idle threads in pool
std::mutex mutex_
Mutex used to access the queue of scheduled jobs.
InitThread init_thread_
Run once per worker thread.