Go to the documentation of this file.
11 #ifndef TLX_THREAD_POOL_HEADER
12 #define TLX_THREAD_POOL_HEADER
16 #include <condition_variable>
67 using Job = Delegate<void ()>;
87 std::atomic<size_t>
busy_ = { 0 };
89 std::atomic<size_t>
idle_ = { 0 };
91 std::atomic<size_t>
done_ = { 0 };
102 size_t num_threads = std::thread::hardware_concurrency(),
141 std::thread&
thread(
size_t i);
150 #endif // !TLX_THREAD_POOL_HEADER
std::mutex mutex_
Mutex used to access the queue of scheduled jobs.
std::atomic< size_t > done_
Counter for total number of jobs executed.
size_t done() const
Return number of jobs currently completed.
void terminate()
Terminate thread pool gracefully, wait until currently running jobs finish and then exit.
std::deque< Job > jobs_
Deque of scheduled jobs.
size_t size() const
Return number of threads in pool.
std::atomic< bool > terminate_
Flag whether to terminate.
simple_vector< std::thread > threads_
threads in pool
void loop_until_empty()
Loop until no more jobs are in the queue AND all threads are idle.
void worker(size_t p)
Worker function, one per thread is started.
std::thread & thread(size_t i)
Return thread handle to thread i.
ThreadPool starts a fixed number p of std::threads which process Jobs that are enqueued into a concur...
Simpler non-growing vector without initialization.
std::condition_variable cv_jobs_
Condition variable used to notify that a new job has been inserted in the queue.
ThreadPool(size_t num_threads=std::thread::hardware_concurrency(), InitThread &&init_thread=InitThread())
Construct running thread pool of num_threads.
~ThreadPool()
Stop processing jobs, terminate threads.
void enqueue(Job &&job)
enqueue a Job, the caller must pass in all context using captures.
std::atomic< size_t > busy_
Counter for number of threads busy.
bool has_idle() const
true if any thread is idle (= waiting for jobs)
size_t idle() const
return number of idle threads in pool
ThreadPool & operator=(const ThreadPool &)=delete
non-copyable: delete assignment operator
void loop_until_terminate()
Loop until terminate flag was set.
std::condition_variable cv_finished_
Condition variable to signal when a jobs finishes.
Delegate< void(size_t)> InitThread
std::atomic< size_t > idle_
Counter for number of idle threads waiting for a job.
InitThread init_thread_
Run once per worker thread.