0

my program with PPL crashes. I do suspect some mishandled share of variables. If my syntax for parallel_for construct is

parallel_for(0,p,[&x1Pt,&x2Pt,&confciInput,&formula,&param,&method,&lowOneParam,&highOneParam](int i)
{   

                 // ...

      }

, do each thread have its own copy of confciInput and formula, for example, to work with? Or does the capture clause of lambda expression only provides access to enclosing scope local variables?

Thanks and regards.

kiriloff
  • 25,609
  • 37
  • 148
  • 229

1 Answers1

2

When you capture a variable by reference in the lambda expression's capture list each thread will operate on the same variable that was captured, and this variable's value is modified in the caller's context. If you need each thread to have its own copy modify the call to

parallel_for(0,p,
  [&x1Pt,&x2Pt,confciInput,formula,&param,&method,&lowOneParam,&highOneParam]
  (int i) mutable
{   
  // ...
} );

Now, each thread has its own copy of the confciInput and formula variables, but any modifications that these threads may make to these local copies will not be made to the original variables.

Also, by default a lambda captures variables by const value, so if you're going to modify either one of variables within the lamda, you'll need the mutable specification.

Praetorian
  • 106,671
  • 19
  • 240
  • 328
  • Thanks, but not compiling. Error on syntax `=confciInput`, `=formula` in capture clause. – kiriloff Apr 30 '12 at 15:14
  • @dlib Oops, messed up the syntax, you don't need to `=`, just the variable name to capture by value – Praetorian Apr 30 '12 at 15:31
  • and what if confciInput is a pointer to a class object? is there a way? – kiriloff Apr 30 '12 at 15:39
  • 1
    @dlib If `confciInput` is a pointer to a class object and you don't want to modify the original, invoke the copy constructor within the body of the lambda to create a local copy. `T confciInputLocal(*confciInput);`' – Praetorian Apr 30 '12 at 18:08
  • Actually, my way to deal with this is the one you describe, which makes me more confident, tks. – kiriloff May 02 '12 at 06:49