Simplest multithreading example
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Aug 31 21:43:29 PDT 2017
On 08/31/2017 06:59 PM, Brian wrote:
> Hello, I am trying to get the most trivial example of multithreading
> working, but can't seem to figure it out.
> I want to split a task across threads, and wait for all those tasks to
> finish before moving to the next line of code.
>
> The following 2 attempts have failed :
>
> -----------------------------------------------------
> Trial 1 :
> -----------------------------------------------------
>
> auto I = std.range.iota(0,500);
> int [] X; // output
> foreach (i; parallel(I) )
> X ~= i;
> core.thread.thread_joinAll(); // Apparently no applicable here ?
As Michael Coulombe said, parallel() does that implicitly.
If the problem is to generate numbers in parallel, I restructured the
code by letting each thread touch only its element of a results array
that has already been resized for all the results (so that there is no
race condition):
import std.stdio;
import std.parallelism;
import std.range;
void main() {
auto arrs = new int[][](totalCPUs);
const perWorker = 10;
foreach (i, arr; parallel(arrs)) {
const beg = cast(int)i * perWorker;
const end = beg + perWorker;
arrs[i] = std.range.iota(beg,end).array;
}
writeln(arrs);
}
If needed, std.algorithm.joiner can be used to make it a single sequence
of ints:
import std.algorithm;
writeln(arrs.joiner);
Ali
More information about the Digitalmars-d-learn
mailing list