Reputation: 160
The following code:
#include <ppl.h>
int i;
vector<int> val(10),summ(10,0);
for(i=0;i<10;i++) val[i]=i;
parallel_for(0, 10, [&] (int y){
vector<int> vett(1000);
double vall=val[y];
for(i=0;i<vett.size();i++)
vett[i]=vall;
for(i=0;i<vett.size();i++)
summ[y]+=vett[i];
});
for(i=0;i<10;i++)
cout<<summ[i]<<endl;
Produces random output like: 0 1000 1468 204 3600 25 5898 7000 7456 1395
I should use "combinable" I guess, but the documentation I found about it is not very good. Do you know how to make this code work correctly? What if vett is a 2d vector?
Since I'd like to learn parallel computing, is it worthy learning this new microsoft library or there are better alternatives?
Upvotes: 1
Views: 485
Reputation: 283921
A good rule of thumb for parallel code is to minimize the number of shared variables.
As a consequence, you should never use [&]
as the lambda capture for parallel_for
(or std::thread
). Capture only the variables that need to be shared.
If you did this, you would have discovered the problem @Blastfurnace pointed out, namely that i
was shared between all workers.
Upvotes: 1
Reputation: 18652
The main problem with your code is the i
subscript variable. It is being used by multiple parallel tasks at the same time. Chaos ensues and is the reason for the wonky results. The simplest fix is to declare the loops in your lambda like this:
for(int i=0;i<vett.size();i++)
vett[i]=vall;
for(int i=0;i<vett.size();i++)
summ[y]+=vett[i];
Note that each loop index is declared in the for
loop initialization. This is more idiomatic usage and can be used in all your loops, unless you really need the final value of i
after the loop is finished.
Upvotes: 2