Parallel
Source: lib/Threads.cs
This page is generated from the source by scripts/gen-reference.py.
Parallel.For: a loop whose iterations run on several threads at once, on the system's threads (pthreads; win/runtime.c maps them to Windows threads).
Parallel.For(0, rows, matrix, static (m, row) => m.ScaleRow(row));
The calling thread works too, and For returns when every iteration is done. Iterations are handed out in chunks from a shared counter, so a thread that finishes early takes more. Starting the workers allocates nothing: the job lives on the caller's stack, which outlives them because For waits.
Where there are no threads (WebAssembly, DOS) or only one processor, or a thread can't be started, the loop simply runs on the calling thread.
What runs in parallel must be safe to: iterations may only write what no other iteration touches, or use Interlocked. Arenas and lib's collections aren't thread-safe: to give each thread its own, split the work into ProcessorCount parts, For(0, Parallel.ProcessorCount, ...), and let each part create its arena. Objects allocated with new are fine: zerocore's allocator is thread-safe, and an arena's AllocateObjectsHere applies only to the thread that opened it. Static constructors are not thread-safe: touch a type's statics once before the loop.
Loops whose iterations run on several threads.
Members
ProcessorCount
public static int ProcessorCount
The number of processors, and so of threads For uses: at least 1.
For
public static void For<TState>(
int from,
int to,
TState state,
Action<TState, int> body)
Runs body(state, i) for every i from from up to but not including to, on up to ProcessorCount threads, and returns when all have run. Pass what the iterations need as state and use a static lambda, so nothing is captured or allocated.