On Saturday, 1 December 2012 at 10:58:55 UTC, thedeemon wrote:

taskPool.parallel is a library function, it doesn't make compiler smarter and doesn't get much help from the compiler. It means your "total" variable will not get any special treatment, it's still a local variable referenced from the loop body which is turned into a function by foreach. This function is run by .parallel in several threads, so you'll get a race condition and most probably an incorrect total value. You should avoid changing the same memory in paralel foreach. Processing different elements of one array (even local) is ok. Writing to one variable not ok.

Humm... So ParallelForeach only launch N tasks doing a work over a slice from the range and nothing more.

The prevois code should work better if i set "total" to be sahred and hope that D shared vars have nnow the internal barries working ,or I need to manually use semaphores ?

import std.stdio;
import std.parallelism;
import std.math;

void main() {
  auto logs = new double[10_000_000];
  shared double total = 0;
  foreach(i, ref elem; taskPool.parallel(logs, 100)) {
    elem = log(i + 1.0);
    total += elem;
  }

  writeln(total);
}

PD: I know that I can use reduction to do the same thing much better...


Reply via email to