View source code
Display the source code in std/parallelism.d from which this page was generated on
github.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.
Requires a signed-in GitHub account. This works well for small changes.
If you'd like to make larger changes you may want to consider using
local clone.
Page wiki
View or edit the community-maintained wiki page associated with this page.
Function std.parallelism.TaskPool.workerIndex
Gets the index of the current thread relative to this
. Any
thread not in this pool will receive an index of 0. The worker threads in
this pool receive unique indices of 1 through TaskPool
this.size
.
This function is useful for maintaining worker-local resources.
Prototype
ulong workerIndex() nothrow @property @safe const;
Examples
// Execute a loop that computes the greatest common // divisor of every number from 0 through 999 with // 42 in parallel. Write the results out to // a set of files, one for each thread. This allows // results to be written out without any synchronization. import std.conv, std.range, std.numeric, std.stdio; void main() { auto filesHandles = new File[taskPool.size + 1]; scope(exit) { foreach(ref handle; fileHandles) { handle.close(); } } foreach(i, ref handle; fileHandles) { handle = File("workerResults" ~ to!string(i) ~ ".txt"); } foreach(num; parallel(iota(1_000))) { auto outHandle = fileHandles[taskPool.workerIndex]; outHandle.writeln(num, '\t', gcd(num, 42)); } }