PIP 5.6.1
Platform-Independent Primitives
Public Member Functions | List of all members
PIThreadPoolLoop Class Reference

Helper that runs one integer range across a fixed set of worker threads. More...

#include <pithreadpoolloop.h>

Public Member Functions

 PIThreadPoolLoop (int thread_cnt=-1)
 Constructs parallel loop runner with thread_cnt worker threads. If thread_cnt is less than or equal to zero, the processor count is used.
 
virtual ~PIThreadPoolLoop ()
 Stops worker threads and destroys the loop runner.
 
void setFunction (std::function< void(int)> f)
 Sets the iteration body called once for each index of a started range.
 
void wait ()
 Waits for the current in-flight batch started by start().
 
void start (int index_start, int index_count)
 Starts asynchronous execution for indices in range [index_start, index_start + index_count).
 
void exec (int index_start, int index_count)
 Runs the configured iteration body for indices in range [index_start, index_start + index_count) and waits for completion.
 
void exec (int index_start, int index_count, std::function< void(int)> f)
 Sets iteration body to f, runs it for indices in range [index_start, index_start + index_count), and waits for completion.
 

Detailed Description

Helper that runs one integer range across a fixed set of worker threads.

Thread pool loop.

This class allow you parallelize loop.

Usage

This class designed to parallel "for(;;)" statement in very simple way. In constructor several threads created, then by setFunction() method you should pass body of your loop, and then call start() or exec(). Every thread take loop counter and execute your function until all counter range is passed.

Example:

PIVector<int> data(10, [](int i)->int{return i;});
piCout << data; // {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
pool.exec(0, data.size(), [&](int i){ // parallel analogue "for (int i = 0; i < data.size(); i++)"
data[i] = data[i] + 10;
});
piCout << data; // {10, 11, 12, 13, 14, 15, 16, 17, 18, 19}
Helper that runs one integer range across a fixed set of worker threads.
Definition: pithreadpoolloop.h:37
void exec(int index_start, int index_count)
Runs the configured iteration body for indices in range [index_start, index_start + index_count) and ...
Definition: pithreadpoolloop.cpp:159
#define piCout
Definition: picout.h:36

Equivalent to:

PIVector<int> data(10, [](int i)->int{return i;});
piCout << data; // {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
pool.setFunction([&](int i){
data[i] = data[i] + 10;
});
pool.exec(0, data.size());
piCout << data; // {10, 11, 12, 13, 14, 15, 16, 17, 18, 19}
void setFunction(std::function< void(int)> f)
Sets the iteration body called once for each index of a started range.
Definition: pithreadpoolloop.cpp:138

Important

Due to multithreading its very important to protect output data of loop body, use mutex. Also remember that execution order is undefined and you shouldnt use global variables in your function. Use local variables and lambda capture.