opensurgsim
Classes | Public Member Functions | List of all members
SurgSim::Framework::ThreadPool Class Reference

A thread pool for completing heterogenous tasks. More...

#include <ThreadPool.h>

Classes

class  Task
 Actual tasks, with typed return type. More...
 
class  TaskBase
 

Public Member Functions

 ThreadPool (size_t numThreads=boost::thread::hardware_concurrency())
 Constructor. More...
 
 ~ThreadPool ()
 Desctructor.
 
template<class R >
std::future< R > enqueue (std::function< R()> function)
 Queue a task to be run by the ThreadPool. More...
 

Detailed Description

A thread pool for completing heterogenous tasks.

The thread pool is a class that completes given tasks using a set of worker threads. These threads pull tasks off of a task queue. Once finished with the task, the thread gets the next task if one is available, or waits for another task to be added. The tasks can be heterogenous, meaning any callable target can be added with any return type.

Example Usage:

double f1() { return 1.0; }
int f2(int val) { return val; }
int main()
{
ThreadPool pool;
// Add a task
std::future<double> result1 = pool.enqueue<double>(f1);
// Add a task using std::bind
std::future<int> result2 = pool.enqueue<int>(std::bind(f2, 2));
// Add a task using a lambda function
std::future<std::string> result3 = pool.enqueue<std::string>([]() {return "string"; });
// Print out result when task is completed
std::cout << "Result 1: " << result1.get() << std::endl;
std::cout << "Result 2: " << result2.get() << std::endl;
std::cout << "Result 3: " << result3.get() << std::endl;
}

Constructor & Destructor Documentation

§ ThreadPool()

SurgSim::Framework::ThreadPool::ThreadPool ( size_t  numThreads = boost::thread::hardware_concurrency())
explicit

Constructor.

Parameters
numThreadsThe number of worker threads

Member Function Documentation

§ enqueue()

template<class R >
std::future< R > SurgSim::Framework::ThreadPool::enqueue ( std::function< R()>  function)

Queue a task to be run by the ThreadPool.

Note
The task must not take any arguments. To add a function that does require arguments use std::bind.
Template Parameters
Rreturn type of the task
Parameters
functionThe task to be queued
Returns
a std::future that holds the results (of type R) once completed

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