Is there a simpler way to do a parallel for-loop in D

99 views Asked by At

Learning D and implementing a ray/path tracer algorithm to solidify the learning. I would like to cast rays in parallel, so this is currently how I have my outer for-loop parallelized:

auto yRange = new int[](imageHeight);
for (auto i = 0; i < imageHeight; ++i)
{
    yRange[i] = i;
}
foreach(ref y; parallel(yRange))
{
    // Inner loop and ray casting...
}

So two questions:

  1. Is there a simpler way to initialize an array in D where each element is the value of its index without using the first for-loop?
  2. Is there a simpler way to parallelize the for-loop? For example, in C++ I could use OpenMP:
#pragma omp parallel for
for (auto y = 0; y < imageHeight; ++y)
{
    // ...
}

Perhaps some way to use a range instead? Something like (syntax obviously wrong)

foreach(ref y; parallel(0..imageHeight))
{
    // ...
}
2

There are 2 answers

0
David Frogley On

I found a simpler way to create the array from a range:

import std.range;
auto yRange = iota(0, imageHeight).array;

So that was helpful.

1
Steven Schveighoffer On

You can use iota as the source range for parallel also:

foreach(y; iota(0, imageHeight).parallel) {
    // ...
}