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

Salih Dincer salihdb at hotmail.com
Tue Apr 4 09:24:26 UTC 2023


On Monday, 3 April 2023 at 22:24:18 UTC, Steven Schveighoffer 
wrote:
> So for example, if you have:
>
> ```d
> foreach(i; iota(0, 2_000_000).parallel)
> {
>    runExpensiveTask(i);
> }
> ```
>
> The foreach is run on the main thread, gets a `0`, then hands 
> off to a task thread `runExpensiveTask(0)`. Then it gets a `1`, 
> and hands off to a task thread `runExpensiveTask(1)`, etc. The 
> iteration is not expensive, and is not done in parallel.
>
> On the other hand, what you *shouldn't* do is:
>
> ```d
> foreach(i; iota(0, 2_000_000).map!(x => 
> runExpensiveTask(x)).parallel)
> {
> }
> ```
>
> as this will run the expensive task *before* running any tasks.

I don't understand what `foreach()` does :)
```d
import std.range, std.algorithm : map;
import std.stdio, std.parallelism;
//import sdb.sequences : RowlandSequence_v2;/*
struct RowlandSequence_v2 {
   import std.numeric : gcd;

   long b, r, a = 3;
   enum empty = false;
   auto front() => a;
   void popFront() {
     long result = 1;
     while(result == 1) {
       result = gcd(r++, b);
       b += result;
     }
     a = result;
   }
}//*/

enum BP : long {
    // s, f, r, b = 7, /* <- beginning
    s = 178, r = 1993083484, b =  5979250449,//*/
    len = 190
}

void main()
{
   with(BP) {
     long[len] arr;
     auto range = RowlandSequence_v2(b, r);

     s.iota(len)
      .map!((a){
                 range.popFront();
                 return arr[a] = range.front();
               }
           )
      .parallel
      .writeln;
   }
} /* PRINTS:

ParallelForeach!(MapResult!(__lambda3, 
Result))(std.parallelism.TaskPool, [5, 3, 73, 157, 7, 5, 3, 13, 
3986167223, 3, 7, 73], 1)

*/
```

Is it necessary to enclose the code in `foreach()`? I invite Ali 
to tell me! Please explain why parallel isn't running.

"Ben anlamıyor, foreach ne yapıyor 😀 Kodu `foreach()` içine almak 
şart mı? Ali'yi davet ediyorum, bana anlatması için! Paralel() 
niye çalışmıyor, lütfen açıklayın hocam. Mümkünse Türkçe!" in 
Turkish.

SDB at 79


More information about the Digitalmars-d-learn mailing list