Standard library · Time and concurrency

pool

Running one loop in parallel across several processor cores.

import pool
On this page
  1. Functions

If each turn of a loop is independent of the others, such as processing each slot of an array on its own, ParallelFor spreads the turns across several worker threads and waits for all of them. The loop body is a function taking an i64, the turn's number.

The order the turns run in is not defined. If the turns change shared data, use a lock or atomic; each turn writing to its own slot is safe.

Functions

CPUCount

func CPUCount(): i64
The number of processor cores, at least one.
pool-ParallelFor.salam
import pool
import mem

mut squares := null as i64*

func main:
    println pool.CPUCount() >= 1
    squares = mem.AllocateZeroed(80 as u64) as i64*
    pool.ParallelFor(10, 4, (i: i64): squares[i] = i * i end)
    mut total := 0 as i64
    repeat 10 in i:
        total += squares[i]
    end
    println total
    pool.ParallelForAuto(10, (i: i64): squares[i] = -i end)
    println squares[9]
    mem.Free(squares as void*)
end
Outputtrue 285 -9

ParallelFor

func ParallelFor(n: i64, workers: i64, body: func(i64))
Runs the body for the numbers zero to n - 1 across workers threads and waits for all of them.

The example for this item is shown with the ones above: pool-ParallelFor.salam

ParallelForAuto

func ParallelForAuto(n: i64, body: func(i64))
Like ParallelFor, with one thread per core.

The example for this item is shown with the ones above: pool-ParallelFor.salam