user2485710
user2485710

Reputation: 9811

Can't wrap my head around parallel_for from tbb

#include <tbb/concurrent_vector.h>
#include <tbb/parallel_for.h>
#include <random>

#define N 1000000

int main()
{
    tbb::concurrent_vector<u_int32_t> v(N);

    std::mt19937 mt;
    std::uniform_int_distribution<u_int32_t> dist(0,499);

    tbb::parallel_for( tbb::blocked_range<tbb::concurrent_vector<u_int32_t>>(v.begin(),v.end()),[&]{return dist(mt);});

    return(0);

}

I don't get why this is isn't working, It's my understanding that the interface for this parallel_for should include the startpoint of the container, the endpoint and the size of the step that should be performed at each iteration of the loop, the last argument it's the function that it will be executed.

now tbb::blocked_range it's used to split the container ( right ? ), so it should be useful in this case, I can't get this to work and I don't get why this just doesn't work with iterators in a much simpler way ...

Upvotes: 0

Views: 2263

Answers (2)

Massa
Massa

Reputation: 8992

What you really want seems to be:

tbb::parallel_for( tbb::blocked_range<tbb::concurrent_vector<u_int32_t>::iterator>(v.begin(),v.end()),[&](tbb::blocked_range<tbb::concurrent_vector<u_int32_t>::iterator>&){return dist(mt);});

Maybe a typedef is necessary here and there :D

int main() {
    typedef tbb::concurrent_vector<u_int32_t> vector;
    vector v(N);

    std::mt19937 mt;
    std::uniform_int_distribution<u_int32_t> dist(0,499);

    typedef tbb::blocked_range<vector::iterator> range;
    tbb::parallel_for( range(v.begin(),v.end()),[&](range& r){for(auto& i: r) { i = dist(mt); } });

    return(0);
}

is fairly better :D

Upvotes: 1

yohjp
yohjp

Reputation: 3135

I would like to use iterators, v.begin() and v.end() or tbb::blocked_range, I would like to avoid the use of constants and try to implement this with reusable components and try to be more c++-ish

TBB has parallel_for_each function template for iterator based loop.

#include "tbb/parallel_for_each.h"

tbb::parallel_for_each(v.begin(), v.end(),
  [&](u_int32_t& e) {
    e = /*...*/; 
  }
);

Upvotes: 5

Related Questions