Parallel loops, a bounded worker pool, goroutine-style tasks, error groups and futures.
import pool
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 package also has a long-lived, bounded worker pool, the Salam answer to goroutines. spawn starts one operating-system thread per call with no limit; a Pool starts its threads once and never more, keeps at most queue tasks waiting, and makes Submit wait when the queue is full, so a fast producer cannot pile up unbounded work. Go runs a task on a shared pool sized to the cores, Group limits how many tasks run at once and keeps the first error, and Async hands back a Future you can Await. To receive from several channels, see Select in chan.
Tasks are threads, not green threads: a task that blocks keeps its worker busy, so a task must not wait for a task queued behind it. Use SubmitOrRun when tasks submit tasks. For shared state, use sync and atomic.
The things people get wrong:
•
Relying on the order of the turns, or changing shared data from them without a lock. Each turn writing to its own slot is safe; anything else needs atomic or a mutex.
•
Making the turns too small. Taking the next turn number costs a lock, and every call starts and joins threads, so a turn should do a fair amount of work (see chunks).
•
Calling ParallelFor in a hot loop. Each call pays for creating threads; parallelize the outer loop instead of the inner one.
One turn per row
The natural fit for ParallelFor is data laid out in rows, such as the pixels of an image or the lines of a table. Make each turn handle one row: the turns touch different memory, so they need no lock, and the result is the same whatever order they ran in.
pool-guide-pixels.salam
import pool
import mem
importstrmut pixels := nullasint*
width := 8
height := 6funcbrighten_row(y: i64):
repeat width in x:
i := (y asint) * width + x
mut v := pixels[i] + 60if v > 255:
v = 255end
pixels[i] = v
endendfuncmain:
pixels = mem.AllocateZeroed(size(int) * ((width * height) asu64)) asint*
repeat width * height in i:
pixels[i] = (i * 37) % 256end
pool.ParallelFor(height, 3, (y: i64): brighten_row(y) end)
repeat height in y:
mut line := ""repeat width in x:
line = line + str.FromInt(pixels[y * width + x]) + " "endprintln line.Trim()
end
mem.Free(pixels asvoid*)
end
The loop body here is a short lambda that calls a named function. Keeping the real work in a named function makes it easy to test on its own, without any threads.
Chunks, not single items
Each turn has a small cost of its own, so a million turns that each add one number spend more time on bookkeeping than on adding. Cut the work into a few large chunks instead, let each turn handle one chunk and write its partial result to its own slot, and combine the slots on the main thread at the end.
pool-guide-chunks.salam
import pool
import mem
mut partial := nullasi64*
total_numbers := 1000000asi64
chunks := 8funcadd_chunk(c: i64):
size := total_numbers / (chunks asi64)
first := c * size + 1mut last := first + size - 1if c == chunks asi64 - 1:
last = total_numbers
endmut s := 0asi64mut n := first
until n <= last:
s += n
n++
end
partial[c] = s
endfuncmain:
partial = mem.AllocateZeroed(size(i64) * (chunks asu64)) asi64*
pool.ParallelForAuto(chunks, (c: i64): add_chunk(c) end)
mut sum := 0asi64repeat chunks in c:
sum += partial[c]
endprintln"chunks:", chunks
println"sum of 1 to", total_numbers, "=", sum
println"check:", sum == total_numbers * (total_numbers + 1) / 2
mem.Free(partial asvoid*)
end
Output
chunks: 8
sum of 1 to 1000000 = 500000500000
check: true
ParallelForAuto picks the number of workers from the processor count. A few chunks per worker is a good size: enough for the work to even out when some chunks are slower, few enough that the overhead stays small.
Combine results with an atomic counter
When the turns produce something that has to be added into one place, such as a count of matches, the simplest safe choice is an atomic.I64. Here every number below 100000 is one turn, and each turn that finds a prime adds one to the shared counter.
pool-guide-primes.salam
import pool
import atomic
mut found := atomic.I64 {}
funcis_prime(n: i64): bool:
if n < 2:
retfalseendmut d := 2asi64until d * d <= n:
if n % d == 0:
retfalseend
d++
endrettrueendfuncmain:
found = atomic.NewI64(0)
pool.ParallelFor(100000, pool.CPUCount(), (n: i64): ifis_prime(n): atomic.Add(found, 1) endend)
println"primes below 100000:", atomic.Load(found)
atomic.DestroyI64(found)
end
Output
primes below 100000: 9592
An atomic add per match is fine when matches are rare compared with the work of each turn. If every turn would update the counter, use partial results per chunk as in the previous section instead.
Rules for the loop body
•
Never rely on the order of the turns. Turn 5 can finish before turn 0.
•
A turn may write to its own slot freely. Anything shared needs a sync.Mutex or an atomic.
•
Do not print from the loop body; the lines come out mixed up. Store the results and print after ParallelFor returns.
•
ParallelFor waits for every turn, so as soon as it returns all results are ready and no join is needed.
•
Small loops are faster without threads. Parallelize only when one run of the loop takes noticeable time.
A set of tasks with a limit on how many run at once and a shared first error.
Name
Type
Description
state
void*
The internal state of the group.
pool-Group.salam
import pool
funccheck(n: int): str:
if n == 7:
ret"item 7 is bad"endret""endfuncmain:
g := pool.NewGroup(3asi64)
repeat20in i:
pool.GroupGo(g, (): retcheck(i) end)
endprintln pool.GroupWait(g)
println pool.GroupFailed(g)
pool.GroupStop(g)
end
The condition that wakes whoever waits for the result.
pool-Future.salam
import pool
funcfib(n: i64): i64:
if n < 2:
ret n
endretfib(n - 1) + fib(n - 2)
endfuncmain:
p := pool.New(2asi64, 4asi64)
a := pool.Async(p, (): retfib(25asi64) end)
b := pool.AsyncStr(p, (): ret"done"end)
println pool.Await(a)
println pool.AwaitStr(b)
println pool.Ready(a)
pool.Release(a)
pool.Release(b)
pool.Stop(p)
end
Runs the body for the numbers zero to n - 1 on workers new threads, at most n of them, and returns when every turn is done. Nothing happens when n is zero or less.
funcNewElastic(min: i64, max: i64, queue: i64): Pool
Like New, but starts with min workers and adds one, up to max, whenever tasks are waiting and every worker is busy. It never exceeds max and never shrinks. Use it when tasks may block on each other.
pool-Elastic.salam
import chan
import mem
import pool
mut box := chan.Chan {} as chan.Chan<i64>
mut got := nullasi64*
funcwaiter():
mut ok := false
v := box.Recv(ok)
atomic_store(got, v)
endfuncsender():
box.Send(7asi64)
endfuncmain:
box.Init(1asi64)
got = mem.AllocateZeroed(8asu64) asi64*
p := pool.NewElastic(1asi64, 4asi64, 8asi64)
println"start: ", pool.Workers(p)
pool.Submit(p, (): waiter() end)
pool.Submit(p, (): sender() end)
pool.Wait(p)
println"received: ", atomic_load(got)
println"grew: ", pool.Workers(p) > 1println"capped: ", pool.Workers(p) <= 4
pool.Stop(p)
box.Free()
mem.Free(got asvoid*)
end
Calls the function for 0 to n - 1 on up to workers threads and returns the results in order.
pool-Map.salam
import pool
funcmain:
squares := pool.Map(10asi64, 4asi64, (i: i64): ret i * i end)
println"count: ", squares.Len()
mut total := 0asi64repeat squares.Len() in i:
total += squares.Get(i)
endprintln"sum: ", total
println"first and last: ", squares.Get(0), squares.Get(9)
println"empty: ", pool.Map(0asi64, 4asi64, (i: i64): ret i end).Len()
end