foreach (i; taskPool.parallel(0..2_000_000)

Ali Çehreli acehreli at yahoo.com
Sat Apr 1 22:48:46 UTC 2023


On 4/1/23 15:30, Paul wrote:

 > Is there a way to verify that it split up the work in to tasks/threads
 > ...?

It is hard to see the difference unless there is actual work in the loop 
that takes time. You can add a Thread.sleep call. (Commented-out in the 
following program.)

Another option is to monitor a task manager like 'top' on unix based 
systems. It should multiple threads for the same program.

However, I will do something unspeakably wrong and take advantage of 
undefined behavior below. :) Since iteration count is an even number, 
the 'sum' variable should come out as 0 in the end. With .parallel it 
doesn't because multiple threads are stepping on each other's toes (values):

import std;

void main() {
     long sum;

     foreach(i; iota(0, 2_000_000).parallel) {
         // import core.thread;
         // Thread.sleep(1.msecs);

         if (i % 2) {
             ++sum;

         } else {
             --sum;
         }
     }

     if (sum == 0) {
         writeln("We highly likely worked serially.");

     } else {
         writefln!"We highly likely worked in parallel because %s != 
0."(sum);
     }
}

If you remove .parallel, 'sum' will always be 0.

Ali



More information about the Digitalmars-d-learn mailing list