Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Nav
New Contributor I
121 Views

parallel_for_each with std::list?

Jump to solution
I have a rather large program which stores pointers to objects in a list. I thought of using parallel_for_each to process each object in the list.

So tried a small program:
[cpp]#include
#include
#include
using namespace std;
using namespace tbb;

class Item
{
   int i;
public:
   Item() {}
   Item(int ii):i(ii) {}
   Item(const Item& old) {i = old.i;}
   void doSomething() {printf("Whoopee I'm doing something! %d\n",i);}
};

class Doer
{
public:
   Doer() {}
   void operator()(Item* item) const//INFO: program won't work without this const
   {
      item->doSomething();
   }
};

int main()
{
   list v;
   for(int i=0;i<10000;++i) v.push_back(new Item(i));
   
   Doer d;   
   parallel_for_each(v.begin(), v.end(), d);
}[/cpp]

The program outputs all 10000 values of i without any problem.

As far as I read about parallel_for_each, it is supposed to always requires random access iterators. But std::list does not support random access iterators. Then how did my program work?

I've even seen the internals of how parallel_for_each is implemented (you use a parallel_do and spawn tasks). The do_task_iter class uses Iterator middle = my_first + k/2; and as I understand, the value held by 'Iterator middle' may become erroneous if it isn't a random access iterator? Correct?

So can I use std::list with parallel_for_each or not?
0 Kudos
1 Solution
Alexey_K_Intel3
Employee
121 Views
Yes you can.

parallel_for_each minimally requires input iterators. It's parallel_for that requires random access iterators.

View solution in original post

2 Replies
Alexey_K_Intel3
Employee
122 Views
Yes you can.

parallel_for_each minimally requires input iterators. It's parallel_for that requires random access iterators.

View solution in original post

Nav
New Contributor I
121 Views
Thanks :) ............
Reply