bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
bitsim::utils::concurrency::ThreadPool Class Reference

A fixed number of threads that run the tasks given to them, in the order given. More...

#include <thread_pool.h>

Inheritance diagram for bitsim::utils::concurrency::ThreadPool:
Collaboration diagram for bitsim::utils::concurrency::ThreadPool:

Public Member Functions

 ThreadPool (uint_t n_threads=0)
 Start n_threads threads; 0 means default_n_threads().
 ~ThreadPool ()
 Run the tasks still queued, then join the threads.
uint_t size () const noexcept
 The number of threads.
bool is_worker_thread () const noexcept
 Whether the calling thread is one of this pool's threads.
template<typename F, typename... Args>
auto submit (F &&f, Args &&...args) -> std::future< std::invoke_result_t< F, Args... > >
 Queue f(args...) to run on one of the threads.

Static Public Member Functions

static uint_t default_n_threads ()
 The number of threads to use when none is given: the environment variable BITSIM_NUM_THREADS if it is a positive number, otherwise the number of cores.

Detailed Description

A fixed number of threads that run the tasks given to them, in the order given.

submit() returns a std::future for the task's result; an exception the task throws comes out of the future's get(). The destructor runs the tasks still queued, then joins the threads.

Most code needs only parallel_for() and parallel_map() in bitsim/utils/concurrency/parallel.h, which use default_thread_pool().

Constructor & Destructor Documentation

◆ ThreadPool()

bitsim::utils::concurrency::ThreadPool::ThreadPool ( uint_t n_threads = 0)
explicit

Start n_threads threads; 0 means default_n_threads().

◆ ~ThreadPool()

bitsim::utils::concurrency::ThreadPool::~ThreadPool ( )

Run the tasks still queued, then join the threads.

Member Function Documentation

◆ default_n_threads()

uint_t bitsim::utils::concurrency::ThreadPool::default_n_threads ( )
static

The number of threads to use when none is given: the environment variable BITSIM_NUM_THREADS if it is a positive number, otherwise the number of cores.

◆ is_worker_thread()

bool bitsim::utils::concurrency::ThreadPool::is_worker_thread ( ) const
noexcept

Whether the calling thread is one of this pool's threads.

A task that waits for other tasks of its own pool can leave no thread to run them; parallel_for() checks this and runs serially inside a task.

◆ size()

uint_t bitsim::utils::concurrency::ThreadPool::size ( ) const
inlinenoexcept

The number of threads.

◆ submit()

template<typename F, typename... Args>
auto bitsim::utils::concurrency::ThreadPool::submit ( F && f,
Args &&... args )->std::future< std::invoke_result_t< F, Args... > >

Queue f(args...) to run on one of the threads.

Returns
the future of its result

The documentation for this class was generated from the following files: