(std parallel)

Reference

Overview

Work on the parts of a collection at the same time, on threads made for work that uses a core.

(import (std parallel))

;; The parts' results, combined in order.
(in-parallel (range 0 10) (fun (part) (loop (:for i part) (:acc v (vecing (* i i))))))
;; [0 1 4 9 16 25 36 49 64 81]

;; The parts' results, one for each part, joined by the caller.
(vec-fold + 0L (in-parts (range 0 1000000)
                         (fun (part) (loop (:for i part)
                                           (:acc s (summing (cast long i)))))))
;; 499999500000L

;; The parts of one array, written in place at the same time.
(: (-> (Span double) void))
(defun (double-all! s)
  (loop (:for i (range 0 (span-length s)))
        (:do (span-set! s i (* 2.0 (span-ref s i))))))

(def xs (make-array 1000000 #:fill 1.5))
(ignore (in-parts xs (fun (part) (double-all! (part->span part)))))

;; A collection of the same type, joined by the module.
(par-map (fun (x) (* x x)) [1 2 3 4])              ; [1 4 9 16]
(par-filter even? (vec->array [1 2 3 4]))          ; #[2 4]

A Chunkable collection splits into parts that together hold each element once, in the collection’s order when it has one. in-parts runs a function on each part on the compute threads, and returns a vector of the results, in the order of the parts. in-parallel does the same and returns the results combined, in the order of the parts, by Combinable of (std combine). A number is not Combinable: sum the results of in-parts, or return a type that combines.

The functions over a whole collection join the parts themselves. par-map and par-filter return a collection of the type they are given, with the elements in its order. par-for-each runs a function on each element.

Implementations. Range, Vec, Array, IArray, Map, HashSet, OrderedMap and OrderedSet. A part of a range is a range. A part of a vector is a vector that shares the vector’s nodes, cut at all points in one call. A part of an array is an ArrayPart, and a part of an immutable array is an IArrayPart: views that hold the array and two indices, not a copy of the elements. A list has no implementation, because a split must traverse it. Use list->vec first.

Maps and sets. A part of a map or a set is a map or a set of the same type and comparer, which shares the tree’s nodes. The split cuts along the nodes: it makes some new nodes on the way down to each cut, and visits no leaf. So the parts’ sizes are close, not equal, and a tree of one leaf, up to 64 entries in an ordered map, is one part. A part counts its entries when its length is first asked for, in the thread that asks. The parts of an ordered map or set are in key order. The parts of a hash map or set are in no order that means anything, and their sizes are close only when the hashes are spread.

Writing in place. part->span gives a span of a part’s elements that writes into the array. The parts of one array do not overlap, so their spans can be written at the same time with no lock. A span cannot be captured by a closure or go to another thread, so the function makes the span from its part, and gives it to a named function.

The compute threads. The parts run on threads made at the first call and kept: one less than the logical cores, and at least one, or as many as the environment variable BJOLANG_COMPUTE_THREADS says. The core left over is for the calling thread, which takes parts too in ordinary code, and for the fibers. Each is a spawn/thread that takes jobs from an inbox, and a job runs in the dynamic environment of the call that made it. They are not the threads that run fibers, so a part holds no run queue.

They share the cores with the threads that run fibers. Measured with bjostat’s bench/latency.bjo, 24 logical cores (Ryzen 9 5900X, a KVM guest), a loop in 24 parts again and again: a fiber that sleeps 1 ms wakes 0.32-0.42 ms late at the median and up to 1.9-2.7 ms with the default 23 compute threads, and up to 7.2-8.6 ms with 24. With 16 it wakes 0.14 ms late at the median, at 10% fewer loops. A program that must answer on time while it computes, such as a server, sets fewer. bench/bjolang/parallel-latency.bjo measures it.

When it is faster. One call with 24 parts that do nothing takes about 8 us at the median and 16 us on average when the compute threads worked less than 50 us before, and about 26 us when they sleep (Ryzen 9 5900X, in a KVM guest), most of it the wake of a thread that sleeps. The default is four parts for each compute thread. Work below some tens of microseconds is faster in sequence. Work that is bound by memory, such as a sum or a scale of a large array of doubles, stops at the memory bandwidth. Work that is bound by computation scales with the physical cores. bench/bjolang/parallel.bjo has the measurements.

The functions over a whole collection gain most when each part only writes, as par-map of an array does, or computes much for each element. Parts that allocate many small nodes, as the parts of a vector or a map do, are bound by the garbage collector with the default .NET settings. bench/bjolang/parallel-collections.bjo has the measurements, and bench/bjolang/parallel-work.bjo how the gain grows with the work for each element.

Generic code. A generic function iterates the parts of any Chunkable through a pin of the part type: (where (Chunkable %c #:chunk %p) (Iterable %p #:elem %e)), as par-for-each does. The form with a projection, (Iterable (assoc Chunkable chunk %c)), is not accepted yet. And a lambda whose parameter is a part does not get the element type from the pin: give the part to a named function.

See also: Chunkable, in-parallel, in-parts, computing-each, par-map, par-filter, par-for-each, ArrayPart, part->span, part->ro-span

Reference

Types

Functions

Types

Chunkable

trait ↑ Types

Trait for collections that split into ordered parts.

%c
The collection type.

An implementation defines the associated type %chunk, the type of a part, and implements chunk-size and chunks. A function names the part type with a pin: (where (Chunkable %c #:chunk %p)).

See also: chunk-size, chunks, in-parallel

ArrayPart

record ↑ Types

A part of an array: a view of the elements from lo up to hi.

array
The array. Not a copy.
lo
The index of the part's first element.
hi
The index after the part's last element.

An ArrayPart is Iterable: (:for x part) gives the part’s elements in order.

See also: part->span, part->ro-span, part-length

IArrayPart

record ↑ Types

A part of an immutable array: a view of the elements from lo up to hi.

iarray
The immutable array. Not a copy.
lo
The index of the part's first element.
hi
The index after the part's last element.

An IArrayPart is Iterable: (:for x part) gives the part’s elements in order.

See also: iarray-part-length

ParallelMap

trait ↑ Types

Trait for collections whose elements a function can change on the compute threads.

An inline trait over the collection’s type constructor, as Monad is: each call is resolved where it is written, so a call in a bjoroutine suspends its fiber while the parts run.

Implementations. Vec, Array, IArray, Map and OrderedMap. A set has none, as a set of the values of the function needs their Eq or Ord. Use in-parallel with a loop into hash-setting or ordered-setting.

See also: par-map, ParallelFilter

ParallelFilter

trait ↑ Types

Trait for collections whose elements a test can select on the compute threads.

An inline trait over the collection’s type constructor, as ParallelMap is.

Implementations. Vec, Array, IArray, Map, HashSet, OrderedMap and OrderedSet.

See also: par-filter, ParallelMap

Functions

chunk-size

function ↑ Functions

(: chunk-size (-> %c int))

Returns the number of elements of a collection, or a good estimate.

c
The collection.
returns
The number of elements, zero or more.

See also: chunks

chunks

function ↑ Functions

(: chunks (-> %c int (Vec %chunk)))

Splits a collection into about k parts, in order.

c
The collection.
k
How many parts to make.
returns
A vector of parts that together hold each element of c once, in c's order when c has one.

There are fewer than k parts when there are fewer elements than k, and there is always at least one part, which is empty when c is empty. The parts of a range, a vector or an array differ in size by one element at most. The parts of a map or a set are cut along the tree’s nodes, so their sizes are close, not equal, and a small tree is one part.

See also: chunk-size, in-parallel

in-parts

function ↑ Functions

(: in-parts (-> %c (-> %p %r) (#:parts int) (#:size int) (Vec %r)))
(in-parts c f #:parts (* 4 thread-count) #:size 0)

Runs a function on each part of a collection on the compute threads, and returns each part’s result.

c
The collection. It must be Chunkable.
f
The function, called once with each part.
#:parts
How many parts to ask for. Four for each compute thread unless given. The collection may make fewer.
#:size
Instead of #:parts: ask for as many parts as n elements make in parts of this size, rounded up. Zero or less: not given.
returns
A vector of the results of f, in the order of the parts.
(in-parts (range 0 10) (fun (part) (count part)) #:parts 4)   ; [2 3 2 3]
(in-parts (range 0 10) (fun (part) (count part)) #:size 4)    ; [3 3 4]

For work that uses a core. f is an ordinary function: a part runs on a thread, not in a fiber, and cannot suspend. The parts are run by computing-each.

The same parts on every machine. By default the number of parts follows the number of compute threads, so a result that depends on where the parts are cut, such as a sum of doubles, differs between machines. With #:size the parts depend only on the collection. A collection may cut close to the size, not at it: a map or a set cuts along its nodes.

In a bjoroutine, the fiber is suspended until the parts have run, and holds nothing. In ordinary code, the thread takes parts too, and then waits only for the parts that other threads run. So a part can call in-parts itself. Everything the parts wrote is visible to the caller when in-parts returns.

A part runs in the dynamic environment of the call: it sees the caller’s parameters.

When a part raises, the parts not started do not run, and in-parts raises the exception when the parts that started have ended. A part that runs cannot be stopped. In a bjoroutine, a cancelled scope stops the parts that have not started, and the bjoroutine stops waiting at once.

In ordinary code in-parts parks its thread while it waits, and the compiler warns when a bjoroutine reaches such a call. It also warns for a call in a part, where the thread it parks is a compute thread and not one that runs fibers: the compiler cannot see that f runs on another thread.

See also: in-parallel, chunks, part->span, computing-each

in-parallel

function ↑ Functions

(: in-parallel (-> %c (-> %p %r) (#:parts int) (#:size int) %r))
(in-parallel c f #:parts (* 4 thread-count) #:size 0)

Runs a function on each part of a collection on the compute threads, and combines the results in order.

c
The collection. It must be Chunkable.
f
The function, called once with each part. Its result must be Combinable.
#:parts
As for in-parts.
#:size
As for in-parts.
returns
The results of f combined by combine-all, in the order of the parts.
(in-parallel (range 0 6) (fun (part) (loop (:for i part) (:acc v (vecing (* i i))))))
;; [0 1 4 9 16 25]

;; Several accumulators: a tuple combines element by element.
(in-parallel [1 2 3 4]
             (fun (part) (loop (:for x part)
                               (:acc evens (vecing x) #:when (even? x))
                               (:acc odds (vecing x) #:when (not (even? x))))))
;; (Tuple [2 4] [1 3])

The parts run as in-parts runs them: also for exceptions, cancellation and the dynamic environment. The results are combined on the calling thread.

A number is not Combinable, as it may be a sum, a count or a maximum. Sum the results of in-parts, or return a type of one’s own that implements Combinable from (std combine).

To fill an array, make it before the call and let each part of a range or of the array write its own elements; return unit.

See also: in-parts, combine-all, Combinable

computing-each

function ↑ Functions

(: computing-each (-> int (-> int %a) (Vec %a)))
(computing-each n work)

Runs a function of k for each k from 0 to n - 1 on the compute threads.

n
How many parts. Zero or less gives an empty vector.
work
The function, called once with each k: ordinary code that cannot suspend.
returns
A vector of the results, in the order of k.
(computing-each 4 (fun (k) (* k k)))   ; [0 1 4 9]

What in-parallel runs its parts with, for work that is not the parts of a Chunkable collection.

The parts are taken by number by the threads that run parts. The call posts runners, jobs that take parts until none is left, one after the other while a part is left that no runner has taken: at most one for each compute thread, or for each part when there are fewer. So small parts wake few threads. A compute thread with no job spins for 50 us before it sleeps, so a call soon after another starts at once. In a bjoroutine the fiber is suspended while the parts run. In ordinary code the calling thread takes parts too, and then waits only for the parts that other threads have taken. So a part can call computing-each itself, also when every compute thread is busy.

A part runs in the dynamic environment of the call, as call-with-dynamic-environment runs a thunk. When a part raises, the parts not started do not run, and the exception is raised when the parts that started have ended. In a bjoroutine, the parts not started when the scope is cancelled do not run, and Cancelled is raised.

See also: in-parts, compute-thread-count

compute-thread-count

function ↑ Functions

(: compute-thread-count (-> int))
(compute-thread-count)

Returns how many compute threads there are.

returns
The value of BJOLANG_COMPUTE_THREADS when it is a number above 0, or else one less than the number of logical cores, and at least 1.

Read once, when (std parallel) is loaded. The threads themselves are made at the first call of computing-each.

See also: computing-each, in-parallel

part-array

function ↑ Functions

(: part-array (-> (ArrayPart %a) (Array %a)))
(part-array p)

Returns the array that a part is a view of.

p
The part.
returns
The whole array, not only the part's elements.

part-lo

function ↑ Functions

(: part-lo (-> (ArrayPart %a) int))
(part-lo p)

Where a part starts in its array.

p
The part.
returns
The index in the array of the part's first element.

See also: part-hi

part-hi

function ↑ Functions

(: part-hi (-> (ArrayPart %a) int))
(part-hi p)

Where a part ends in its array.

p
The part.
returns
The index in the array after the part's last element.

See also: part-lo

part-length

function ↑ Functions

(: part-length (-> (ArrayPart %a) int))
(part-length p)

Returns the number of elements in a part.

p
The part.
returns
hi minus lo.

part->span

function ↑ Functions

(: part->span (-> (ArrayPart %a) (Span %a)))
(part->span p)

Returns a span of a part’s elements that writes into the array.

p
The part.
returns
A span of the elements from lo up to hi. Index 0 is the part's first element.

Make the span in the function that in-parallel calls: a span cannot be captured by a closure, go to another thread or be kept across a sync.

See also: part->ro-span, in-parallel

part->ro-span

function ↑ Functions

(: part->ro-span (-> (ArrayPart %a) (RoSpan %a)))
(part->ro-span p)

Returns a read-only span of a part’s elements.

p
The part.
returns
A read-only span of the elements from lo up to hi. Index 0 is the part's first element.

See also: part->span

iarray-part-lo

function ↑ Functions

(: iarray-part-lo (-> (IArrayPart %a) int))
(iarray-part-lo p)

Where a part starts in its immutable array.

p
The part.
returns
The index in the immutable array of the part's first element.

See also: iarray-part-hi

iarray-part-hi

function ↑ Functions

(: iarray-part-hi (-> (IArrayPart %a) int))
(iarray-part-hi p)

Where a part ends in its immutable array.

p
The part.
returns
The index in the immutable array after the part's last element.

See also: iarray-part-lo

iarray-part-length

function ↑ Functions

(: iarray-part-length (-> (IArrayPart %a) int))
(iarray-part-length p)

Returns the number of elements in a part of an immutable array.

p
The part.
returns
hi minus lo.

par-for-each

function ↑ Functions

(: par-for-each (-> (-> %e void) %c void))
(par-for-each f c)

Runs a function on each element of a collection, on the compute threads.

f
The function. It runs on the compute threads, at the same time for different parts.
c
The collection. It must be Chunkable, with parts that are Iterable.
(def total (make-atomic 0))
(par-for-each (fun (x) (ignore (atomic-add! total x))) (range 0 100))
(atomic-ref total)   ; 4950

The elements of one part are taken in order, and the parts at the same time. The element of a map’s part is an entry, a Tuple of the key and the value. The parts run as in-parallel runs them.

See also: in-parallel, in-parts

par-map

function ↑ Functions

(: par-map (-> (-> %a %b) (%c %a) (%c %b)))

Returns a collection of the same type with (f x) in place of each element x.

f
The function. It runs on the compute threads, at the same time for different parts.
c
The collection: a vector, an array, an immutable array, a map or an ordered map.
returns
A collection of the same type and length, with the values of f in the order of c.
(par-map (fun (x) (* x x)) [1 2 3 4])               ; [1 4 9 16]
(par-map (fun (v) (+ v 1)) (list->map (list (Tuple "a" 1))))  ; #map(("a" 2))

Of a map or an ordered map, the values are the elements: the keys stay as they are, as with map-map-values.

How the parts are joined:

The parts run as in-parallel runs them: also for exceptions, cancellation and the dynamic environment.

See also: par-filter, in-parallel

par-filter

function ↑ Functions

(: par-filter (-> (-> %a bool) (%c %a) (%c %a)))

Returns a collection of the same type with the elements for which (keep? x) is true.

keep?
The test. It runs on the compute threads, at the same time for different parts.
c
The collection: a vector, an array, an immutable array, a map, a hash set, an ordered map or an ordered set.
returns
A collection of the same type, with the elements kept, in the order of c.
(par-filter even? [1 2 3 4])                  ; [2 4]
(par-filter even? (list->hashset (list 1 2 3 4)))   ; #{2 4}, unordered

Of a map or an ordered map, keep? is given the value. To test the key too, use in-parts with map-filter, and map-merge the parts.

How the parts are joined:

The parts run as in-parallel runs them.

See also: par-map, in-parallel