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

Thread pool loop. More...

#include <pithreadpoolloop.h>

Public Member Functions

 PIThreadPoolLoop (int thread_cnt=-1)
 Contructs thread pool with threads count "thread_cnt". If "thread_cnt" = -1 then system processors count used.
 
void setFunction (std::function< void(int)> f)
 Set threads function to lambda expression "f" with format [ ](int){ ... }.
 
void wait ()
 Wait for all threads stop.
 
void start (int index_start, int index_count)
 Start functions execution with integer argument range from "index_start" to "index_start + index_count - 1".
 
void exec (int index_start, int index_count)
 Start functions execution with integer argument range from "index_start" to "index_start + index_count - 1" and wait for finish.
 
void exec (int index_start, int index_count, std::function< void(int)> f)
 Start functions "f" execution with integer argument range from "index_start" to "index_start + index_count - 1" and wait for finish.
 

Detailed Description

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}
Thread pool loop.
Definition: pithreadpoolloop.h:34
void exec(int index_start, int index_count)
Start functions execution with integer argument range from "index_start" to "index_start + index_coun...
Definition: pithreadpoolloop.cpp:159
#define piCout
Macro used for conditional (piDebug) output to PICout(StdOut)
Definition: picout.h:35

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)
Set threads function to lambda expression "f" with format [ ](int){ ... }.
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.