SMTK  @SMTK_VERSION@
Simulation Modeling Tool Kit
Public Member Functions | Protected Member Functions | Protected Attributes | List of all members
smtk::common::ThreadPool< ReturnType > Class Template Reference

A basic thread pool that executes functors in separate threads. More...

#include <ThreadPool.h>

Collaboration diagram for smtk::common::ThreadPool< ReturnType >:
[legend]

Public Member Functions

 ThreadPool (unsigned int maxThreads=0)
 Initialize thread pool with maxThreads threads spawned to execute tasks.
 
template<typename Function , typename... Types>
std::future< ReturnType > operator() (Function &&function, Types &&... args)
 Add a task to be performed by the thread queue. More...
 

Protected Member Functions

void initialize ()
 
std::future< ReturnType > appendToQueue (std::function< ReturnType()> &&task)
 Append a functor with no inputs to the task queue. More...
 
void execute ()
 Run by a worker thread: poll the task queue for tasks to perform. More...
 
virtual void exec ()
 

Protected Attributes

std::condition_variable m_condition
 
std::mutex m_queueMutex
 
std::vector< std::thread > m_threads
 
std::queue< std::packaged_task< ReturnType()> > m_queue
 
bool m_initialized { false }
 
std::atomic< bool > m_active
 
unsigned int m_maxThreads
 

Detailed Description

template<typename ReturnType = void>
class smtk::common::ThreadPool< ReturnType >

A basic thread pool that executes functors in separate threads.

It accepts the number of threads to build at construction, and waits for all tasks to complete before being destroyed. The ReturnType is a default-constructible type that tasks return via std::future.

Member Function Documentation

◆ appendToQueue()

template<typename ReturnType >
std::future< ReturnType > smtk::common::ThreadPool< ReturnType >::appendToQueue ( std::function< ReturnType()> &&  task)
protected

Append a functor with no inputs to the task queue.

This is used in tandem with std::bind to construct the class's call method.

◆ execute()

template<typename ReturnType = void>
void smtk::common::ThreadPool< ReturnType >::execute ( )
inlineprotected

Run by a worker thread: poll the task queue for tasks to perform.

NOTE: the single layer of misdirection ensures that we launch a thread using the correct method address.

◆ operator()()

template<typename ReturnType = void>
template<typename Function , typename... Types>
std::future<ReturnType> smtk::common::ThreadPool< ReturnType >::operator() ( Function &&  function,
Types &&...  args 
)
inline

Add a task to be performed by the thread queue.

Once a thread becomes available, it will pop the task from the queue and execute it. The return value can be accessed from the returned future.


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