slang::ThreadPool class

A lightweight thread pool for running concurrent jobs.

Constructors, destructors, conversion operators

ThreadPool(unsigned threadCount = 0) explicit
Constructs a new ThreadPool.
~ThreadPool()
Destroys the thread pool, blocking until all threads have exited.

Public functions

auto getThreadCount() const -> size_t
Gets the number of threads in the thread pool.
template<typename TFunc, typename... TArgs>
void pushTask(TFunc&& task, TArgs && ... args)
Pushes a new task into the pool for execution.
template<typename TFunc, typename... TArgs, typename TResult = std::invoke_result_t<std::decay_t<TFunc>, std::decay_t<TArgs>...>>
auto submit(TFunc&& task, TArgs && ... args) -> std::future<TResult>
Submits a task into the pool for execution and returns a future for tracking completion.
template<typename TIndex, typename TFunc>
void pushLoop(TIndex from, TIndex to, TFunc&& body, size_t numBlocks = 0)
Pushes several tasks into the pool in order to parallelize the loop given by [from, to).
void waitForAll()
Blocks the calling thread until all running tasks are complete.
template<typename R, typename P>
auto waitForAll(const std::chrono::duration<R, P>& duration) -> bool
Blocks the calling thread until all running tasks are complete, or until the provided duration is passed.

Function documentation

slang::ThreadPool::ThreadPool(unsigned threadCount = 0) explicit

Constructs a new ThreadPool.

Parameters
threadCount The number of threads to create in the pool. If zero (the default) the number of threads will be set to the number of concurrent threads supported by the system.

template<typename TFunc, typename... TArgs>
void slang::ThreadPool::pushTask(TFunc&& task, TArgs && ... args)

Pushes a new task into the pool for execution.

There is no way to wait for the pushed task to complete aside from calling waitForAll and waiting for all tasks in the pool to complete.

template<typename TFunc, typename... TArgs, typename TResult = std::invoke_result_t<std::decay_t<TFunc>, std::decay_t<TArgs>...>>
std::future<TResult> slang::ThreadPool::submit(TFunc&& task, TArgs && ... args)

Submits a task into the pool for execution and returns a future for tracking completion.

Returns A std::future that will eventually contain the result of the task.

template<typename TIndex, typename TFunc>
void slang::ThreadPool::pushLoop(TIndex from, TIndex to, TFunc&& body, size_t numBlocks = 0)

Pushes several tasks into the pool in order to parallelize the loop given by [from, to).

The loop will be broken into a number of blocks as specified by numBlocks – or if zero, the number of blocks will be set to the number of threads in the pool.

template<typename R, typename P>
bool slang::ThreadPool::waitForAll(const std::chrono::duration<R, P>& duration)

Blocks the calling thread until all running tasks are complete, or until the provided duration is passed.

Returns true if all tasks completed, or false if the timeout was reached first