How works internally ParallelForEach
thedeemon
dlang at thedeemon.com
Sat Dec 1 02:58:54 PST 2012
On Saturday, 1 December 2012 at 10:35:38 UTC, Zardoz wrote:
> auto logs = new double[10_000_000];
> double total = 0;
> foreach(i, ref elem; taskPool.parallel(logs, 100)) {
> elem = log(i + 1.0);
> total += elem;
> }
>
> writeln(total);
> }
>
> I understand that are launched N task, doing a chunk of 100
> elements from logs array. But what happen with "total". There
> is only a "total" and D is using memory barriers / atomic
> operations to write in it ? Or each Task have his own "total"
> and later joint each private "total" in the outside "total".
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.
More information about the Digitalmars-d-learn
mailing list