#include <genesis/utils/core/thread_pool.hpp>
Thread pool for distributed work.
This simple implementation offer a standing pool of worker threads that pick up tasks.
Example
// Create a thread pool with 2 worker threads ThreadPool thread_pool( 2 ); // Enqueue a new task by providing a function and its arguments, and store its future result auto result = thread_pool.enqueue( []( int some_param ) { // do computations int some_result = 42; return some_result; }, 0 // value for `some_param` ); // Get the value of `some_result` from the future // As this is a future, the function call to get() blocks until a thread has finished the work std::cout << result.get() << "\n";
As the workers are stored in the ThreadPool object itself, it does not allow to be copied.
Definition at line 77 of file thread_pool.hpp.
Public Member Functions | |
ThreadPool (size_t num_threads=0) | |
Construct a thread pool with a given number of workers. More... | |
ThreadPool (ThreadPool &&)=delete | |
ThreadPool (ThreadPool const &)=delete | |
~ThreadPool () | |
Destruct the thread pool, stopping and joining any workers that are potentially still running or waiting. More... | |
template<class F , class... Args> | |
auto | enqueue (F &&f, Args &&... args) -> std::future< typename std::result_of< F(Args...)>::type > |
Enqueue a new task, using a function to call and its arguments. More... | |
size_t | load () const |
Return the current number of queued tasks. More... | |
ThreadPool & | operator= (ThreadPool &&)=delete |
ThreadPool & | operator= (ThreadPool const &)=delete |
size_t | size () const |
Return the number of workers of the thread pool. More... | |
|
inlineexplicit |
Construct a thread pool with a given number of workers.
We allow for 0 tasks on construction, so that default construction is possible. However, the enqueue() throws if used with such an instance.
Definition at line 91 of file thread_pool.hpp.
|
delete |
|
delete |
|
inline |
Destruct the thread pool, stopping and joining any workers that are potentially still running or waiting.
Definition at line 136 of file thread_pool.hpp.
|
inline |
Enqueue a new task, using a function to call and its arguments.
The enqueue function returns a future that can be used to check whether the task has finished, or to wait for it to be finished. This also allows the task to send its result back to the caller, if needed, by simply returning it from the task function.
Definition at line 182 of file thread_pool.hpp.
|
inline |
Return the current number of queued tasks.
Definition at line 168 of file thread_pool.hpp.
|
delete |
|
delete |
|
inline |
Return the number of workers of the thread pool.
Definition at line 160 of file thread_pool.hpp.