Recommendation for parallelism with nested for loops?

Christian Köstlin christian.koestlin at gmail.com
Sat Aug 20 18:06:03 UTC 2022


On 20.08.22 12:28, Christian Köstlin wrote:
> On 19.08.22 03:49, Shriramana Sharma wrote:
>> Hello. I want to parallelize a computation which has two for loops, 
>> one nested within another. All inner-loop-param+outer-loop-param 
>> combinations can be computed independent of one another.
>>
>> As I suspected, 
>> [https://forum.dlang.org/post/xysyidbkjdinclmrxzgt@forum.dlang.org](this forum post) says that only one loop can be parallelized. Will it be an error or inefficient or useless if I try to do both?
>>
>> Also, what is the best way to do parallelism in such a situation?
> You could also do a custom range that makes a one-dimensional range (aka 
> iota out of your nested loops) and then process this with parallel.
> Another way (more similar to Ali's solution) would be to write the 
> nested loops as you have them, but collect the parameters for the work 
> in an array or something and then process this array in parallel.
> 
> Kind regards,
> Christian
> 
> 
Actually phobos brings already all that is required (especially the 
cartesian product):

```d
import std;

void doSomething(int i, string s)
{
     writeln("%s-%s".format(i, s));
}

void main()
{
     foreach (t; cartesianProduct(iota(1, 4), ["abc", "def", 
"ghi"]).parallel) {
         doSomething(t.expand);
     }
}
```

kind regards,
Christian



More information about the Digitalmars-d-learn mailing list