|
ADS
Algorithms and Data Structures
|
The headers of include/ADS/parallel realize, beyond the book, the parallel versions of a few algorithms of the library on the threads of one machine with shared memory: the patterns of the loops, of the reductions and of the prefix sums, the merge of sorted ranges and the sort, the products of matrices, the visits of a static graph, the LCP array of a text, the greedy algorithms on graphs by deterministic reservations and the shortest paths, and the runtime of the long-lived workers that talk by messages (their channels, the farm with feedback and the mailbox with the detection of the termination). Each runs on an executor, which is the only part that knows the threads, and gives the result of its sequential version. This page collects what the headers take for granted: the model of the cost and its notation (see Definitions and notation), the executors and the way they schedule the calls (see Executors and schedules), for each family of algorithms the property on which its correctness rests and the argument behind its bound (from Loops, reductions and prefix sums to Shortest paths by steps), and the runtime of the workers (from Long-lived workers and their locks to The detection of the termination). The pseudocode of each algorithm is instead on the page of its header, in the comment of its function, together with the paper that it follows.
A parallel computation is a graph of tasks, oriented and acyclic, with an edge from a task to each task that cannot start before it ends; the fork and join of two calls (parallelInvoke() of Executor.h) and the loop whose iterations are independent (parallelFor()) are the two ways in which the algorithms of the area build it. The work \( W \) is the time of all the tasks, i.e., the time of the computation on one thread, and the depth (or span) \( D \) is the time of a longest path of the graph, i.e., the time on infinitely many threads; their ratio \( W / D \) is the parallelism, the most threads that can be kept busy. An algorithm is work-efficient when its work is, up to a constant factor, the time of the best sequential algorithm: the ones of the area are, save the overheads stated in their headers, so that on one thread they lose only a constant.
| Symbol | Meaning |
|---|---|
| \( p \) | the threads of an executor, its concurrency(), the calling thread included where it works |
| \( W \), \( D \) | the work and the depth of a computation |
| \( T_p \) | the time on \( p \) threads, so that \( T_1 = W \) and \( T_\infty = D \) |
| \( g \), \( B \), \( \bar{B} \) | the grain, i.e., the least number of indices of a block of a loop (kGrain by default), the number of blocks, and the most blocks of a loop (kBlocks by default) |
| \( \oplus \) | an associative operation of a reduction or of a prefix sum, with the identity id or the initial value init |
| \( n \), \( m \) | the items of the input, the nodes and the arcs of a graph |
Two lower bounds hold for any schedule, since \( p \) threads do at most \( p \) units of work in a unit of time and the tasks of a path run one after the other:
\[ T_p \ge W / p , \qquad T_p \ge D . \tag{1} \]
The speedup is \( T_1 / T_p \), at most \( p \) by (1), and it is linear when it is \( \Theta( p ) \), which needs a parallelism \( W / D \) larger than \( p \). The model counts the operations and not the moves of the memory, while several algorithms of the area (the products of a sparse matrix by a vector, the distribution of the sort) are bound by the bandwidth of the memory, which the threads of a socket share; their headers state the number of passes over the memory, on which their speedup depends more than on (1).
An executor runs the calls \( f( 0 ) , \ldots , f( n - 1 ) \) on its threads and returns when all have returned (bulk( n , f ), the concept Executor of Executor.h), and may run two calls in parallel (invoke( f , g )); every parallel algorithm of the library takes one as its first argument, so that the same algorithm runs on any of the five, and on the four over the runtimes that a program may already have (the parallel algorithms of the standard library, the senders of stdexec, Taskflow and Kokkos, in ADS/interop/parallel).
| Executor | Threads | bulk( n , f ) | invoke( f , g ) | A call nested in a call |
|---|---|---|---|---|
| Sequential | the caller | the calls in order | \( f \), then \( g \) | in order |
| ThreadPool | \( p - 1 \) workers and the caller | \( \min\{ p - 1 , n - 1 \} \) tokens on the deque of the caller, stolen by the others, each claiming calls by a fetch-and-add | \( g \) pushed on the deque, \( f \) run, \( g \) taken back unless stolen | on all the threads, any depth |
| FastFlowExecutor | \( p \) workers, the caller waiting | a ParallelFor of FastFlow, chunks of 1 | by bulk() | in order on its thread |
| OpenMPExecutor | \( p \), the caller included, or the team of the caller inside a region | omp parallel for, dynamic chunks of 1, or omp taskloop inside a region | by bulk() on 2 indices | as tasks of the team |
| TBBExecutor | an arena of \( p \), one of the program or the current one, the caller included | parallel_for of oneTBB, a task per index | parallel_invoke | as tasks of the arena |
| StdParExecutor | those of the backend of the standard library | std::for_each of the policy on the indices | by bulk() | as the backend nests |
| SenderExecutor | those of the scheduler | sync_wait() of a bulk sender | by bulk() | in order on its thread |
| TaskflowExecutor | the workers of Taskflow | a graph of one for_each_index, run or co-run | by bulk() | co-run by the worker |
| KokkosExecutor | those of a space of the host | parallel_for of a range, then fence() | by bulk() | in order on its thread |
A call nested in a call that runs in order on its thread is correct on every executor, since a thread may run several calls of a job one after the other and the patterns never make a call wait for one that is not yet claimed (the first block not done of a scan has no block to wait for, and the barrier of the stepping admits the calls that come late). What is lost is the parallelism below the top level: a loop of \( B \) blocks still runs on \( \min\{ p , B \} \) threads, while a recursion by parallelInvoke(), whose top level is one call of bulk() on 2 indices, runs on at most 2, i.e., in time at least \( W / 2 \) in place of \( W / p + D \). It is the price that SenderExecutor and KokkosExecutor pay, since their wait holds the thread that waits and a nested wait would hold all of them.
Lemma 1 (the greedy schedule). A schedule that never leaves a thread idle while a task is ready runs in
\[ T_p \le W / p + D , \tag{2} \]
within a factor of 2 of the best, by (1) (Graham, and Brent for the computations of known depth).
Indeed, at each unit of time either all the \( p \) threads work, which can happen at most \( W / p \) times, or some thread is idle; in the second case every ready task runs, and the first task of each longest path among the tasks left is ready, so that the depth of what is left decreases by 1, which can happen at most \( D \) times. The patterns of Executor.h approach the greedy schedule from the side of the data: a loop is cut into \( B \) blocks, which the threads claim one at a time from a counter, so that a thread is idle only when no block is left, and the time is \( T_p \le W / p + \max_b w_b \) for blocks of work \( w_b \). With blocks of equal work \( W / B \) this is \( ( W / p ) ( 1 + p / B ) \), and the cut into at most \( \bar{B} \) blocks (kBlocks = 64 by default) of at least kGrain indices trades this loss against the cost of a claim, a fetch-and-add on a shared line.
The pool of ADS (ThreadPool) schedules by work stealing: each thread keeps its tasks on a deque of Chase and Lev, takes them from the bottom, and, when it has none, steals the oldest of a random other thread. With work stealing the expected time is \( W / p + O( D ) \) (Blumofe and Leiserson): a thief that fails is charged to the depth, since each round of \( p \) steals makes progress on the critical path with constant probability, and the thread that works is charged to the work; the expected number of steals is \( O( p D ) \), and since a steal moves the oldest task, which in a fork and join is the largest, the steals are few when the parallelism is large. The job of bulk() pushes \( \min\{ p - 1 , n - 1 \} \) tokens that the thieves take one at a time and that claim the calls from a shared counter, so that its calls are balanced as in the dynamic schedule and no task is allocated; invoke() waits for a stolen call by running other tasks (the leapfrogging of Wagner and Calder), so that a thread that waits still works and the bound holds for the nested calls too.
The bounds above count the units of work, not where they run: a thread that the system moves to another processor finds there cold caches, and on a machine of several sockets the memory it touched first stays on the node of the old one. Affinity.h gives the processors that the process may use, as taskset or numactl left them, and pins the calling thread to the \( i \)-th of them (modulo their number), so that the workers of a pool that pin themselves at their start fill those processors in order and keep them; the executors do not pin their threads by themselves, since two programs pinned to the same processors would slow each other down, and the choice is left to the caller.
The blocks of a loop (blocksOf() of Executor.h) depend only on the number of indices, on the grain and on the most blocks \( \bar{B} \): \( s = \max\{ g , \lceil n / \bar{B} \rceil \} \) indices per block and \( \lceil n / s \rceil \) blocks. parallelReduce() reduces each block by a call f( lo , hi ) into a partial result and combines the partial results by \( \oplus \) in the order of the blocks, so that its result is
\[ \mathit{id} \oplus r_0 \oplus r_1 \oplus \cdots \oplus r_{B - 1} , \qquad r_b = f( \mathit{lo}_b , \mathit{hi}_b ) , \tag{3} \]
whatever the executor and the number of its threads; (3) is the sum by blocks, which equals the sum from left to right when \( \oplus \) is associative, and is the same on every executor also when \( \oplus \) is associative only up to rounding, as the sum of floating point numbers is. The reduction has work \( O( n ) \) and depth \( O( n / B + B ) \), the blocks and then their combination.
The prefix sums \( y_i = x_0 \oplus \cdots \oplus x_i \) (or up to \( x_{i-1} \), the exclusive ones) are the pattern of the counting sorts, of the compaction of a vector and of the distribution of the parallel sort. The scan of Blelloch reduces the blocks, scans the \( B \) partial results and then scans each block from its prefix, i.e., it reads the input twice and writes the output once, \( 3 n \) moves. parallelInclusiveScan() and parallelExclusiveScan() do it in one pass by the decoupled look-back of Merrill and Garland: the threads claim the tiles in increasing order, reduce each tile \( c \) into its aggregate \( a_c \), publish it, and add on the left the values published by the tiles before it until one has published its inclusive prefix \( P_{c'} \), so that
\[ P_c = P_{c'} \oplus a_{c' + 1} \oplus \cdots \oplus a_{c - 1} \oplus a_c ; \tag{4} \]
then they publish \( P_c \) and scan the tile from the prefix before it, which is still in the cache: \( 2 n \) moves.
Lemma 2 (the look-back ends). The scan by decoupled look-back ends on any executor, and its prefixes are those of the scan from left to right.
In fact, a thread waits only for a tile before its own, and the tiles are claimed in increasing order: a tile before \( c \) is held by a thread that runs, since it claimed it before \( c \) was claimed, and the least tile not done waits for no tile, since all the tiles before it have published their prefix. Hence, by induction on the tiles, each tile is done, also when the threads of the executor are fewer than the tiles or when one runs all of them in order (Sequential). The prefixes are right by (4) and the associativity of \( \oplus \), since the tiles from \( c' + 1 \) to \( c - 1 \) added on the left are exactly those after the last prefix met. The look-back reads \( O( 1 ) \) tiles on average when the threads go at the same pace, since the tile before is then about to publish its prefix, and at most \( c \) tiles; an exception in a tile publishes it as failed, so that the tiles after it stop instead of waiting.
The merge of \( k \) sorted ranges of \( N \) items in all (multiwayMerge() of ParallelMerge.h) is cut into \( B \) parts of the output, each merged by the sequential merge on one thread; it rests on the following.
Lemma 3 (the multisequence selection). Order the items by the triples \( ( \mathit{item} , \mathit{range} , \mathit{position} ) \). For each rank \( r \le N \) there is a unique split \( s( r ) \), with
\[ \sum_{i = 1}^{k} s_i( r ) = r , \tag{5} \]
such that the first \( s_i( r ) \) items of each range \( i \) are the \( r \) least items, and the merge writes them, in its order, before the others.
Indeed, the order of the triples is total and, within a range, it is the order of the positions, since the range is sorted; hence the \( r \) least triples are a prefix of each range, and the order of the triples is the order of the stable merge, which on equal items takes the range of lower index first. The part \( q \) of the output is then the merge of the pieces \( [ s_i( r_q ) , s_i( r_{q+1} ) ) \) of the ranges, written from the rank \( r_q \), and the parts are independent. multisequenceSplit() finds \( s( r ) \) by narrowing a window on each range: the pivot is the middle of a window, chosen as the median of the middles weighted by the widths, and the binary searches that place it in the other windows tell whether it is among the \( r \) least. If it is, every window whose middle is not larger loses its left half, and these windows weigh at least half of the total width by the choice of the median; otherwise the same holds on the right. At least a quarter of the total width goes at each step, hence there are \( O( \log( k N ) ) \) steps, each of \( k \) binary searches and of a sort of \( k \) middles, i.e., \( O( k \log N \log( k N ) ) \) comparisons per split, far fewer than the \( O( N \log k ) \) of the merge. With \( B = 4 p \) parts the merge takes \( O( ( N / p ) \log k ) \) time plus the splits, which run in parallel.
The parallel sorts of ParallelSort.h (sort( ex , A , less ) and stableSort( ex , A , less )) first look for the inputs that need no distribution: a reduction by blocks finds whether \( A \) is sorted or in decreasing order, and a second one whether it is made of a few runs per block, which are merged by the merge above. Otherwise they distribute the items into \( k \) buckets whose concatenation is sorted, as the samplesort does: \( k - 1 \) splitters taken from a sorted random sample of \( 16 k \) items (oversampling, so that every bucket holds \( O( n / k ) \) items with high probability), or the highest bits of the keys of the numbers in their natural order. The classification is a parallel loop on the blocks, each counting its items per bucket; a prefix sum of the counts in the order (bucket, block) gives each block the place of its items of each bucket, and a second loop moves them there, the blocks in their order, so that the distribution is stable. Last, the buckets are sorted by the sequential sort, claimed from the largest down (the schedule LPT of Graham, within \( 4 / 3 \) of the best), and a bucket larger than \( n / p \) is sorted by the parallel sort itself. With \( k \) buckets the time is \( O( n / p + k p ) \) for the classification and \( O( ( n / p ) \log( n / k ) ) \) for the buckets when they are balanced, and each item moves a constant number of times. The learned sorts of the same header (learnedSort( ex , A ) and learnedStableSort( ex , A )) change the classifier only: on numbers of 32 or 64 bits, the bucket of a key is read from a model of the distribution function of a sample (see LearnedSort.h), a grid whose cell leaves a few comparisons with no branch instead of the \( \log_2 k \) dependent steps of the tree, and the sort falls back on the classifiers above when the sample shows a distribution that the model does not fit; the bound is the same, since the model keeps the buckets balanced with high probability by the same argument of the sample.
The product of a sparse matrix of \( m \) rows and \( \mathit{nnz} \) nonzeros by a vector (multiply() of ParallelNumeric.h) costs, for the row \( i \), its nonzeros plus the store of its sum, i.e., the rows up to \( i \) cost \( i + \mathit{start}( i ) \), which grows with \( i \). Hence the cut of this quantity into \( B \) equal parts, each found by a binary search, balances the parts (the diagonals of the merge path of Merrill and Garland, applied to whole rows), and each row is summed on one thread in the order of the sequential product, so that the result is the same bit for bit; only a row longer than a part makes the parts unequal. The product moves \( 12 \mathit{nnz} + 8 ( m + n ) \) bytes for \( 2 \mathit{nnz} \) operations, i.e., it is bound by the bandwidth of the memory, and its speedup is at most the ratio of the bandwidth of the socket to that of one core. The product of dense matrices (gemm()) is instead bound by the operations, \( 2 m n k \): with the backend of a CBLAS it is one call of it, which runs on its own threads and packs its own panels (Smith et al. describe how the threads of such a library share them); without it, each thread takes a range of the rows of \( C \) and runs on it the loops of the sequential product by blocks of \( 256 \) columns and \( 256 \) rows of \( B \) (kGemmBlock), read in place from the matrix that all the threads share, with nothing packed, so that the sums of each entry run in the order of the common index and the result is that of the sequential product, bit for bit.
The levels of a visit in breadth are
\[ L_0 = \{ s \} , \qquad L_{\ell + 1} = \{ v \notin L_0 \cup \cdots \cup L_\ell : ( u , v ) \in E \text{ for some } u \in L_\ell \} , \tag{6} \]
and a node of \( L_\ell \) is at distance \( \ell \) from \( s \) (by Lemma 1, see Visits). bfsDistances() of ParallelGraph.h builds each level by (6) in either direction: from the top down, the nodes of \( L_\ell \) claim their neighbors not yet reached by a compare-and-swap of the distance, which succeeds for one claimant only and writes the same level whoever wins; from the bottom up, each node not yet reached looks for one neighbor in \( L_\ell \), and stops at the first. Both give the set (6), and hence the same distances; they differ in the arcs they read, the arcs out of the frontier \( m_f \) against those into the nodes not yet reached up to their first hit, at most \( m_u \). The visit goes from the bottom up when \( m_f > m_u / \alpha \), which happens on the few large levels of the graphs of small diameter, and back when the frontier is small again (Beamer, Asanovic and Patterson). The work is \( O( n + m ) \), each level costs a depth of \( O( \log n ) \) to gather its frontier, and the depth is therefore \( O( D \log n ) \) for diameter \( D \).
The connected components (connectedComponents()) are those of a concurrent MFSET in which a merge hooks the larger of two roots under the smaller by a compare-and-swap, and tries again from the new roots if another thread moved first. The parent of a node is then never larger than the node, hence the parents form no cycle, the root of a set is its least node, and after the merges of all the arcs the sets are the components, whatever the order of the merges. The sampling of Afforest (Sutton, Ben-Nun and Barak) skips most of the merges: after the merges of the first two arcs of each node, a sample of nodes finds the largest set \( c \), and the nodes of \( c \) merge no more. On an unoriented graph this loses no arc between two components, since such an arc has an end out of \( c \), which merges it; the arcs within the giant component, usually most of them, are never read.
The LCP array of a text \( T \) of \( n \) symbols and of its suffix array \( \mathit{SA} \) (lcpArray() of ParallelText.h) is read from the permuted array \( \mathit{PLCP}[ i ] = \mathrm{lcp}( i , \Phi[ i ] ) \), \( \Phi[ i ] \) the suffix before \( i \) in the order of \( \mathit{SA} \), which has
\[ \mathit{PLCP}[ i ] \ge \mathit{PLCP}[ i - 1 ] - 1 . \tag{7} \]
In fact, if the suffixes \( i - 1 \) and \( \Phi[ i - 1 ] \) share a prefix of \( h > 0 \) symbols, the suffix \( \Phi[ i - 1 ] + 1 \) comes before \( i \) and shares \( h - 1 \) symbols with it, and so does every suffix between them in the order, \( \Phi[ i ] \) included. By (7) a scan of \( i \) in the order of the text resumes each comparison at \( h - 1 \), and since \( h \) grows by at most \( n \) in all and decreases by 1 per suffix, it makes \( O( n ) \) comparisons (Kasai et al.). The parallel version cuts the text into \( 4 p \) parts, each scanned from \( h = 0 \): (7) is then not used across the borders, which costs at most \( \max_i \mathit{PLCP}[ i ] \) more per part and leaves the result the same.
A greedy algorithm scans its items in a fixed order and decides each of them on the state that the earlier ones left, e.g., the algorithm of Kruskal keeps an edge if no earlier edge joined its ends (see Minimum spanning trees). The deterministic reservations of Blelloch, Fineman, Gibbons and Shun (speculativeFor() of SpeculativeFor.h) run such a loop of iterations \( s , s + 1 , \ldots , e - 1 \) on the threads of an executor, each iteration \( i \) split into two steps: \( \mathrm{reserve}( i ) \) reads the state and either finds that \( i \) has nothing to do or writes \( i \) into a reservation of each place of the state that it would change, by a priority write that keeps the least index there; and \( \mathrm{commit}( i ) \) changes the state if \( i \) holds all its reservations, and otherwise leaves \( i \) to the next round. A round runs the reserves of a prefix of \( r \) iterations not yet done, in parallel, then their commits in parallel, and keeps the failed ones, in their order, at the head of the next prefix.
Lemma 4 (determinism of the reservations). Assume that (i) each \( \mathrm{reserve}( i ) \) reserves every place that \( \mathrm{commit}( i ) \) may change, but for the places that no other iteration changes or reserves; (ii) for each place \( p \) that \( i \) reads and each other iteration \( j \) that may change \( p \), either \( i \) reserves \( p \), or \( j < i \); (iii) \( \mathrm{commit}( i ) \) changes the state and returns true if \( i \) holds all its reservations and every \( j < i \) of the second case of (ii) was done before the round of \( i \), and otherwise changes nothing. Then the least iteration of each round commits, and the state at the end is the one of the sequential loop, whatever the executor and the number of its threads.
Indeed, a round takes the iterations not yet done in their order, so that every iteration before the least one of a round is done, and the least one wins every priority write and commits by (iii). If \( i \) commits and \( j \ne i \) may change a place \( p \) that \( i \) reads or changes, either \( i \) reserves \( p \), and then so does \( j \) by (i), so that an earlier \( j \) in the round of \( i \) would hold \( p \) and a later one in a round with \( i \) never holds it; or \( i \) only reads \( p \), and \( j < i \) was done before the round by (ii) and (iii). Hence \( i \) reads and writes the values of the sequential loop before \( i \). The failures depend only on the state and on the least index of each reservation, not on the timing of the threads; hence the sequence of the rounds, and the size \( r \) of their prefixes, which halves when more than a fifth of a round fails and doubles when less than a tenth does, are themselves deterministic. The maximal matching meets (ii) by its first case, the maximal independent set by its second, and the forests of Kruskal, whose commit needs one of its two reservations, have an argument of their own (below).
With \( W \) the work of the sequential loop and \( R \) that of the iterations tried again, the work is \( O( W + R ) \) and the depth is that of the rounds, each of depth \( O( \log r ) \) for the pack of the failures. For the maximal independent set and the maximal matching in a random order the iterations that wait for each other form chains of length \( O( \log n ) \) with high probability (Blelloch, Fineman and Shun gave \( O( \log^2 n ) \), and Fischer and Noever the tight bound), so that few iterations fail and the rounds are few.
ParallelGreedy.h builds on the reservations the greedy algorithms of the table below, each with the result of its sequential version on the same order. In parallelKruskal() the edge \( i \), in the order of \( ( w( e ) , e ) \), reserves the roots of its ends in a union-find if they differ, and its commit hangs the root that it holds under the other. A root is held only by the least iteration that reserved it, and hence the links of a round form no cycle (around one, each iteration would precede the next), and an iteration that holds a root had no earlier iteration of its round on either root, so that the sequential algorithm takes its edge too. The finds run while no link happens, so that the halving of their paths writes values that a concurrent find reads either way. filterKruskal() (Osipov, Sanders and Singler) splits the edges by a pivot \( p \) into the light ones \( e < p \) and the heavy ones, solves the light ones first, and then drops, by a parallel filter, the heavy edges whose ends the forest already joins, before their recursion; a heavy edge dropped would be refused by Kruskal too, and the light edges come first in the order, so that the forest is the same, while the edges dropped are never sorted. In maximalIndependentSet() the reserve of a node looks at its neighbors of earlier places, one in the set leaving it out and one undecided making it wait, and in maximalMatching() an edge reserves its two ends if both are free and takes them if it holds both.
| Function | Order | Work |
|---|---|---|
| parallelKruskal() | \( ( w( e ) , e ) \), by the parallel sort | \( O( m \log m ) \) |
| filterKruskal() | as above, sorting only the edges not filtered | \( O( m + n \log n \log( m / n ) ) \) expected on random weights |
| spanningForest() | the order of the edges | \( O( m \, \alpha( m , n ) ) \) plus the retries |
| maximalIndependentSet() | a permutation \( \pi \) of the nodes | \( O( n + m ) \) expected on a random \( \pi \) |
| maximalMatching() | a permutation \( \pi \) of the edges | \( O( n + m ) \) expected on a random \( \pi \) |
The shortest paths from \( s \) with costs that are not negative (see Shortest paths) are the least solution of
\[ d( s ) = 0 , \qquad d( u ) = \min\bigl\{ d( u ) , \min_{( v , u ) \in E} d( v ) \oplus w( v , u ) \bigr\} , \tag{8} \]
where \( \oplus \) is the sum of the computer, which for the integers is the sum and for the floating points is the sum rounded, in both cases monotone, \( a \le b \Rightarrow a \oplus w \le b \oplus w \), and not decreasing, \( a \oplus w \ge a \) for \( w \ge 0 \).
Lemma 5 (the label-correcting steps). Start from \( d( s ) = 0 \) and \( d( v ) = \infty \) elsewhere, with \( s \) active, and repeat, in any order and with any number of threads, steps that take some active nodes, make them not active, and relax their arcs, each relaxation \( d( u ) \gets \min\{ d( u ) , d( v ) \oplus w( v , u ) \} \) atomic and making \( u \) active (adding it to a bucket, or setting its flag) if it lowers \( d( u ) \). When no node is active, \( d \) is the least solution of (8), the distances of the algorithm of Dijkstra.
Indeed, each \( d( u ) \) is at every moment the value of a path from \( s \) summed by \( \oplus \) from \( s \), and hence at least the least solution, which is the least such value; and when no node is active, every arc was relaxed after the last decrease of its tail, which by the monotonicity left \( d( u ) \le d( v ) \oplus w( v , u ) \) on it, so that \( d \) solves (8), and being at least the least solution, it is the least. The algorithm of Dijkstra computes the same solution, since by the two properties of \( \oplus \) its order of extraction never lowers the distance of a node already extracted. A node made active while it is being relaxed is relaxed again: the flag that says whether it is active is cleared before its distance is read, and a relaxation that lowers the distance reads the flag after it, both sequentially consistent, so that one of the two sees the other.
The algorithms differ in the nodes that each step takes. The algorithm of Dijkstra takes one, the least, and relaxes each arc once; that of Bellman, Ford and Moore by rounds takes all the active nodes, \( O( n ) \) steps of large frontiers, and relaxes an arc as many times as its tail improves. The \( \Delta \)-stepping of Meyer and Sanders (deltaStepping() of ParallelShortestPaths.h) takes the active nodes in the bucket \( \lfloor d / \Delta \rfloor \) of the least active distance \( \mu \), again while the bucket is not empty: a node of a later bucket has a distance at least the end of the bucket, and since the costs are not negative it lowers no distance within it, so that the nodes of the bucket are at their final distances when it is empty, and the extra work is that of the nodes of the bucket relaxed before they reached them. For costs independent and uniform in \( [ 0 , 1 ] \) and \( \Delta \) of the order of the inverse of the largest degree \( d \), Meyer and Sanders bound the expected work by \( O( n + m + d L ) \) and the depth by \( O( d L \log n + \log^2 n ) \), \( L \) the largest distance.
The steps of deltaStepping() are those of the GAP benchmark suite (Beamer, Asanović and Patterson; the code of Beamer and Zhang): each thread appends the nodes that it improves to buckets of its own, with no flag, so that a node is in a bucket once per improvement and is skipped, when its bucket comes, if its distance has meanwhile fallen below it (it was then relaxed in an earlier bucket, by Lemma 5 at its last distance); a step relaxes the frontier of the bucket \( c \), then each thread its own bucket \( c \) while it is small, and the threads meet at a barrier, vote the next bucket, copy their parts of it into the frontier, each at the places that the counts of the others give it, and meet at a second barrier. Two barriers a step, against the seven passes of a step that gathers its frontier by blocks, is what makes the steps of a graph of large diameter cheap, where most steps hold a few hundred nodes. The threads are those of the calls of one bulk() of the executor, which run the whole computation; a call that starts late joins it at a barrier, which counts the threads that joined at its release. Hence a barrier waits only for calls that are running, each of which reaches it, and the computation ends on any executor, also on one that runs the calls one after the other, where the first call does all the work and the others find it over. The buckets of a thread are a window of 1024 buckets from a base and an overflow past it, which the threads spread over the next window when the least bucket voted is past the current one (the open buckets of Julienne, of Dhulipala, Blelloch and Shun), so that the memory does not grow with \( L / \Delta \). With \( \Delta \) above the least costs a node improves many times within its bucket and is put back into it each time, and its entries would relax its arcs again at a distance already relaxed: from the step where the entries put back into the bucket of the step outnumber a quarter of those relaxed, each node keeps the distance at which it was last relaxed, and an entry that finds its node at that distance relaxes nothing. This is safe whatever the threads, since the arcs of a node at a distance are relaxed by whoever stored it, before the barrier that ends the step, and it costs a read and a write per entry, which is why it starts only when the entries put back show that it pays.
The \( \rho \)-stepping of Dong, Gu, Sun and Zhang (rhoStepping()) takes the \( \rho \) active nodes of least distance, or all of them when they are no more than \( \rho \), with the threshold estimated on a sample of 1024 of them, so that the steps have a frontier of the same size whatever the scale of the costs; on a graph whose frontier stays below \( \rho \), e.g., a grid or a road network, it is the algorithm of Bellman, Ford and Moore by rounds, and a smaller \( \rho \) is needed there. Each of its steps costs \( O( \log n ) \) depth for the gathering of its frontier, so that the steps should be few; the nodes that a block of arcs makes active within the threshold of its step are relaxed by the same block at once, up to 1024 of them, as in the fusion of the buckets of Zhang et al., which saves the steps of the chains of light arcs.
The calls of bulk( n , f ) are tasks: an executor may run several of them on one thread, one after the other, and a call starts only when a thread is free to take it, so that a call that waits for another one (at a barrier, or for a message) may wait forever for a call that no thread will start before it returns. A computation of workers, each a loop that lives as long as the computation and talks to the others (the workers of a parallel search, each with its own queue of nodes and its inbox, or the master and the workers of a farm), needs instead that its \( p \) calls all begin, each on a thread that holds no other one, so that calls that wait for each other run at the same time on \( p \) distinct threads; run( p , f ) of the executors with workers (the concept WorkerExecutor of Executor.h) gives this (a call that returns before the others have begun may leave its thread to one of them), together with lock_type, the mutex that the executor prefers for the short sections that the workers share. Every lock_type is Lockable in the sense of the standard, i.e., it has try_lock() besides lock() and unlock(), which takes the lock only if it is free and never waits: a worker that finds a shared section busy (the update of a common bound, the publication of a part of its work) may then skip it and come back later, instead of queueing behind the holder.
| Executor | The calls | Why they run together | lock_type |
|---|---|---|---|
| Sequential | \( f( 0 ) \) on the caller, \( p \le 1 \) | one worker | std::mutex |
| ThreadPool | \( f( 0 ) \) on the caller, the others claimed one each under a mutex by the workers idle in their loop | a thread that waits inside a call never claims one | std::mutex |
| OpenMPExecutor | a region omp parallel of \( p \) threads, \( f( i ) \) on its thread \( i \) | the team has \( p \) threads, or nothing runs and run() throws | OpenMPLock, i.e., omp_lock_t |
| TBBExecutor | a parallel_for of the arena, a task per call, each call inside isolate() | a thread that waits inside a call takes only the tasks of the jobs nested in it | tbb::spin_mutex |
| FastFlowExecutor | a parallel_for of its ParallelFor on \( p \) workers, chunks of 1 | each worker is given its own index first | FastFlowLock, i.e., ff::lock_t |
A worker that binds itself to a processor (to keep its caches, and its memory on its node) must not bind the thread of the caller, which goes on after the run with the placement the program gave it; isRunCaller() of Executor.h tells a call whether it runs on that thread. The caller makes \( f( 0 ) \) on Sequential, ThreadPool and OpenMPExecutor (the thread 0 of a region of OpenMP is the thread that opens it), none of the calls on FastFlowExecutor with \( p > 1 \), where it only waits, and on TBBExecutor any one of them or none, since it joins the arena as one more thread; since the calls run at the same time on distinct threads, the caller holds at most one of them, and the mark is a variable of the thread set for the time of the run, so that a worker that asks costs a load.
Lemma 6 (the calls of a run meet). Let a pool of ThreadPool have \( p - 1 \) workers idle in their loop besides the thread that calls run( p , f ). Then the \( p \) calls run at the same time, each on its own thread, whatever the calls do, nested jobs included.
Indeed, the caller makes \( f( 0 ) \), and the other calls are claimed one at a time from a counter under a mutex, only by a worker that is in its loop, i.e., that holds no call of any job; a worker that has claimed a call makes it and goes back to its loop only after it has returned, so that no thread holds two calls of the run. A thread that waits inside a call, for a job nested in it or for the end of the run, steals and runs only tasks, never a call of the run: were it to run one, it would hold it below its own call, which might wait for it forever. Hence the \( p - 1 \) idle workers claim the \( p - 1 \) calls, one each, as soon as they wake (the run wakes the sleeping ones through the event count of the pool), and all the calls run together. On the other executors the same property rests on the runtime: the team of a region of OpenMP has its \( p \) threads from the start; a thread of oneTBB inside isolate() takes only the tasks spawned within it, and the arena has \( p \) threads when the threads of oneTBB are not fewer, i.e., for \( p \) not larger than the hardware threads; the ParallelFor of FastFlow cuts \( [ 0 , p ) \) into \( p \) chunks of 1, one per worker, and a worker looks at the chunks of the others only after its own, so that a worker takes the call of another only when its own has returned, which leaves the calls that wait for each other on distinct workers.
Each of \( p \) workers has an inbox, into which the others push batches of messages and which only its owner drains; the messages of a sender to a receiver come out in the order in which they were pushed, while those of different senders interleave in any order. A batch of \( k \) messages is pushed by one operation of the channel, so that the cost of the synchronization (an atomic operation, a lock, a line of cache that moves between two cores) is paid once per batch and not per message; the four families of Channels.h differ in what they pay and when.
| Family | Push | Drain | Bounded | Memory |
|---|---|---|---|---|
| LockedChannels | a lock, \( k \) copies, a store of the size | a load of the size; if not 0, a lock and a swap of two vectors, then \( k \) calls | no | the messages |
| InboxChannels | a vector of \( k \) copies, a cell, one compare-and-swap | one exchange, the list of the \( b \) batches reversed, \( k \) calls | no | the messages, a cell and a vector per batch |
| LaneChannels | \( k \) stores with a release, no read-modify-write | the \( p \) lanes in turn, a read of the count per block, \( k \) calls | no | \( p^2 \) lanes of blocks |
| MeshChannels | \( k \) copies, one store of a tail | the \( p \) queues of the worker, a load of a tail and a store of a head each, \( k \) calls | yes, \( c \) per pair | \( p^2 c \) places |
The inboxes under a lock are the baseline that every executor can build with its own lock, and the only family whose memory does not depend on the pairs of workers; a sender and the owner meet on the lock, and senders meet among themselves. The stack of Treiber of InboxChannels makes the push of a batch lock-free, one compare-and-swap whatever \( k \), and the drain one exchange whatever the number of senders, at the price of an allocation per batch. The lanes of LaneChannels and the mesh of MeshChannels give each ordered pair of workers a queue of its own, so that two senders never touch the same line and a push needs no read-modify-write, the queues of the farms and of the all-to-all of FastFlow; a drain then scans the \( p \) queues of its worker, \( O( p ) \) loads even when they are empty, and the memory grows as \( p^2 \), which on the threads of one machine (tens of workers) is cheap. The mesh is bounded: a push that finds its queue full pushes what fits and returns the number, and the mailbox keeps the rest in its outbox (see The detection of the termination), so that a worker is never blocked by a receiver that does not drain. On the benchmark (bench/runtime.cpp, 4 and 8 workers on the pool, on OpenMP and on FastFlow, one per core, messages of 8 bytes) the mesh is the fastest family whenever the workers exchange batches: with batches of 64 messages it takes 1.4 to 2.5 times less per message than the inboxes under a lock (whichever lock), 3 to 4.5 times less than the stacks of batches and the lanes, and 1.9 to 2.7 times less than the mesh of the queues of FastFlow, which pass a pointer per message with a store of a flag each; with batches of 1 message it takes 2 to 5 times less than the inboxes under a lock, while the mesh of FastFlow is then within 0.7 to 1.8 times of it. A round trip of one message between two workers costs the mesh 1.1 to 1.7 times less than the inboxes under a lock, and the lanes pay there the wait of their consumer for a batch; the exploration of a tree spread over the workers, whose work per message dominates, is a tie among the families within the noise of the machine, the lanes and the stacks last. Hence DefaultChannels is the mesh on every executor, the inboxes under the lock of the executor stay the portable choice whose memory does not grow with \( p^2 \), and the lanes and the stacks of batches remain for the senders that cannot bound what they push.
A farm with feedback has a master, which emits tasks, and \( w \) workers, which turn each task into a result that goes back to the master; the master may emit more tasks from each result, and decides when the farm ends. It is the master and workers of FastFlow (a farm whose emitter receives the results of its workers on the channel of feedback), and feedbackFarm() of Farm.h runs it on a farm of FastFlow on FastFlowExecutor, and on run( w + 1 , f ) of the other executors, the master being the call 0. The tasks go to the workers on demand, i.e., a task waits in a queue of many consumers [see MPMCQueue.h] until a worker is free, which balances tasks of different costs; the results come back on a queue with a lane per worker [see MPSCQueue.h].
The workers have the indices \( 0 , \ldots , w - 1 \) and the master the index \( w \), which work( t , i ) and start( emit , w ) receive when they take them, so that each may keep a state of its own (an evaluator, a buffer, the processor to which it binds itself) in a vector of \( w + 1 \) places without a lock. An index stays on one thread for the whole farm, and distinct indices on distinct threads: on FastFlow the master is the emitter and the worker \( i \) the \( i \)-th node of the farm, each a thread of FastFlow; on the other executors the master is the call 0 of run( w + 1 , f ) and the worker \( i \) the call \( i + 1 \), which Lemma 6 keeps on distinct threads for the whole run.
| Executor | Master, index \( w \) | Worker \( i \) |
|---|---|---|
| FastFlowExecutor | the emitter, a thread of FastFlow | the node \( i \), a thread of FastFlow |
| ThreadPool, OpenMPExecutor | the caller | the call \( i + 1 \) of the run, a thread of the executor |
| TBBExecutor | the calls \( 0 \) and \( i + 1 \) of the run, on threads of the arena, the caller among them or not | |
| any, \( w = 0 \) | the caller, which is the master and the worker 0 | |
Lemma 7 (the farm ends). If work() returns on every task and the master emits finitely many tasks, the farm ends, and when it ends because no task is left the master has seen the result of every task it emitted.
Indeed, the master counts in \( m \) the tasks emitted and not yet back: it adds 1 at each emission and subtracts 1 at each result, and a worker that takes a task always sends back a result (empty if the farm was stopped or the work threw), so that \( m \) is the number of the tasks in the queue, in the hands of a worker, or of their results in the queue back. While \( m > 0 \) some task or result exists, and since the free workers take the tasks and work() returns, the master receives a result in finite time; it emits finitely many tasks, so that \( m \) reaches 0, and then nothing is left to receive. When the master stops the farm instead, the workers end after the task they hold, whose result is dropped.
In a computation by messages a worker is active while it has work, and passive otherwise; a passive worker becomes active only by receiving a message, and only an active worker sends. The computation has terminated when every worker is passive and no message is on its way, a state that lasts forever once reached (no worker can become active again), but that no worker sees by itself: a worker that has no work does not know whether a message for it is still on its way, or whether another worker is about to send one. The detection of the termination is the problem of Dijkstra and Scholten, who solved it for a computation that starts from one process with an acknowledgment of every message and a tree of the active processes, and of Mattern, who counted the messages sent and received with waves that read the counters of all the processes (see Messages, owners and termination for the processes of MPI).
In shared memory the counters can be one: the mailbox of Mailbox.h keeps a counter \( C \) of the activities and of the messages, which starts at \( p \) (every worker active). A worker adds \( k \) to \( C \) before it pushes a batch of \( k \) messages (and subtracts the messages that a bounded channel refused); a passive worker that drains messages adds 1 before it handles the first of them, and becomes active; a worker subtracts the \( k \) messages it drained once it has handled them; a worker that has no work and has pushed all its outboxes becomes passive and subtracts 1. The messages still in an outbox are not counted, but their sender is active, and it becomes passive only after it has pushed them.
Lemma 8 (the deficit counter). At any time
\[ C \ge A + M , \tag{9} \]
\( A \) the number of the active workers and \( M \) that of the messages pushed and not yet handled; and \( C = 0 \) if and only if the computation has terminated and every worker has seen it, i.e., has subtracted its activity.
Indeed, every change of \( A + M \) is preceded by the change of \( C \) that covers it: a batch is added before it is pushed, an activity is added before the messages that bring it are handled, and the messages and the activities are subtracted only after they have ended; the operations on \( C \) are atomic, so that they follow each other in one order, and (9) holds after each of them. If \( C = 0 \), (9) gives \( A = 0 \) and \( M = 0 \), and no outbox holds a message, since its owner would be active: the computation has terminated, and since every increase of \( C \) is made by an active worker or for a message, \( C \) stays at
No operation of the mailbox waits for another worker. A bounded family (the mesh) may take only part of a batch, when the queue of the pair is full: the rest stays in the outbox, counted by nobody, while its owner stays active; send() tries it again only when a batch more has come for that destination, so that a full queue costs the sender one push, i.e., two atomic additions on \( C \), per batch and not per message, and flush() tries every outbox and returns false while one is not empty.
Lemma 9 (the batches retained). Let each worker whose quiescent() returns false poll its inbox before it calls quiescent() again. Then every message retained in an outbox is pushed in finite time, and Lemma 8 holds as it is.
Indeed, a worker with a message in an outbox fails its flush(), stays active and holds its activity in \( C \), so that (9) and the argument of Lemma 8 do not change: the retained messages are not in \( M \), but their sender is in \( A \). A queue is full only of messages pushed and not yet drained, and its receiver drains all its queues at each poll; since every worker polls between two calls of quiescent(), each full queue is emptied in finite time, and the next flush() of the sender pushes into it. A cycle of workers each waiting to push into the queue of the next one cannot block, since none of them waits: each polls, which empties the queue that its predecessor waits for.
A computation may also end before its termination, when one of its workers, or another thread, knows that the rest of the work is useless: a limit on the work done, or a bound that closes the search. stop() sets a flag that every operation reads: from then on quiescent() and terminated() return true, poll() drains nothing, send() only appends to its outbox and flush() pushes nothing. The messages on their way are not lost: once the workers have returned from run(), leftovers() hands to a function those of the outboxes and those of the inboxes, which a search puts back into its frontier, where they bound the optimum of what was not explored.
Lemma 10 (each message once). Whatever the moment of stop(), also during the sends and the polls of the workers, each message given to send() is handed to a function exactly once, by a poll() before the stop or by leftovers() after the run.
Indeed, a message is at any time in exactly one of three places: an outbox, which only its sender touches; a channel, between a push and a drain; or handed to a function. It moves from the first to the second only by a push of its sender, which copies it into the channel and removes it from the outbox in the same operation of that thread, and from the second to the third only by a drain of its receiver, which moves it out of the queue and calls the function on it; a push or a drain started before the flag is set runs to its end, and none starts after the flag is seen. Hence when the workers have returned no message is moving, each is in an outbox, in a channel or already handed, and leftovers(), which empties the outboxes and drains the channels on the thread that called run() (which the end of the run orders after every operation of the workers), hands each of the first two kinds once.
A mailbox serves a sequence of computations separated by barriers (the phases of an episode of an incremental search, or its episodes): rearm(), called by one thread at the barrier, sets the activity of each worker as asked and \( C \) to the number of the active workers, and withdraws the stop, keeping the channels and the outboxes, so that a phase costs \( O( p ) \) instead of the construction of the \( p^2 \) queues of the mesh.
Lemma 11 (the rearm). Let rearm() be called at a barrier, with the outboxes empty and either \( C = 0 \) or the mailbox stopped and emptied by leftovers(). Then Lemmas 8 and 10 hold for the computation that follows, with \( A \) the workers made active.
Indeed, no message exists at the call: the outboxes are empty, and the channels too, since \( C = 0 \) gives \( M = 0 \) by (9), while after a stop leftovers() has drained them. After rearm(), \( M = 0 \) and \( C = A \), so that (9) holds with equality, as at the construction, and the barrier orders the writes of rearm() before every operation of the next computation; the arguments of Lemmas 8 and 10 do not depend on how many workers are active at the start, provided every worker with work from the start is among them.
A worker of a search sends many messages for the same key between two pushes (the relaxations of one state by its neighbors, each with its own distance), of which the receiver keeps only one, the least; the mailbox of the policy CoalesceBy merges them in the outbox, before they cost a place in the channel and a call at the receiver. send( me , to , x , merge ) looks up the key of \( x \) in a map of the outbox, from a key to the place of the last message of that key sent with a merge since the last push; if there is one, merge( pending , x ) merges \( x \) into it, or refuses, and \( x \) is then appended and becomes the last of its key, as it does when there is none. One probe of the map does both the search and the update. A plain send( me , to , x ) closes the run of the key of \( x \): by one probe it marks the key \( \bot \) in the map, and the next send of that key with a merge finds \( \bot \), merges into nothing and is appended after \( x \); with NoCoalescing the plain send makes no probe. A push that the channel takes \( j > 0 \) messages of removes the first \( j \) of the outbox and shifts the others by \( j \) places, so it empties the map; a push refused whole moves nothing, and keeps it.
Lemma 12 (the coalescing). Let each merge be made by send() with a merge, with a function that does not throw and does not change the key of the message pending. Then (i) the map gives, for each key, either the place in the outbox of the last message of that key sent with a merge since the last push that took a message, if that message is still there and no message of that key was sent without a merge after it, or \( \bot \) if one was, and no other place, so that no message of a key is merged into one sent before a message of that key sent without a merge; (ii) Lemmas 8, 9 and 11 hold as they are, and Lemma 10 holds with each message given to send() either handed once or merged, by a merge counted by merged(), into a message handed once; (iii) a message \( x \) merged into a pending message \( y \) reaches the receiver with \( y \), in a batch pushed after the call that sent \( x \), so that every write of the sender before that call happens before the receiver handles \( y \).
Indeed, (i) holds at the start, with the outbox and the map empty, and is kept by each operation of the owner, the only one to touch them: a send with a merge either merges into the place it finds, which removes the new message and changes neither the places nor the keys, or appends at the end and records that place for its key, the last one of that key; a send without a merge appends past every place recorded and marks its key \( \bot \), so that the next send of that key with a merge, finding \( \bot \), merges into nothing and records a place past it; a push that takes \( j > 0 \) messages empties the map, so that no place survives the shift, and one that takes none changes neither; leftovers() empties the outbox and the map together. For (ii), a merge acts only on the outbox of its caller, whose messages are not counted in \( C \), which counts a message only from the addition before its push (Lemma 8): the message merged is removed before it is ever counted, while \( y \) stays where it was, uncounted. Hence a merge changes neither \( C \), nor \( A \), nor \( M \), and (9) with the argument of Lemma 8 is unchanged; it does not lengthen an outbox, so that a flush() succeeds no later than without it, and Lemma 9 is unchanged too. After a stop the merges go on in the outboxes, which leftovers() hands as they are, and the three places of the proof of Lemma 10 receive every message once, but for those merged, which leave the computation inside the outbox of their sender and are counted there; the outboxes empty, the maps are empty by (i), so that rearm() leaves no place of a past computation and Lemma 11 holds. For (iii), \( y \) is in the outbox when \( x \) is sent, hence not yet pushed; the push that later takes it is made by the same thread after the call, and the release of the push with the acquire of the drain gives the order of the writes, as for a message not merged.
The merged message keeps the place of \( y \), so that \( x \) overtakes the messages of other keys sent between them, but by (i) never one of its own key sent without a merge. The order among the messages of one key is that of the runs that a refused merge or a plain send closes: a merge refused for \( x \) appends it as the last of its key, and the messages of that key sent later merge into it, or after it, never into one before it. Whether the receiver may see the merged message in place of the two is the consumer's to prove, e.g., for the relaxations of a search by the least distance (a dominated relaxation changes nothing), and for an invalidation between two relaxations of a state, which is sent without a merge, or refused by the merge, so that it stays between them.
An incremental computation by messages (the repair of a search after the costs of some arcs changed) keeps a state that must equal what a computation from scratch would give, and an audit compares them; but the state of a worker changes while messages are on their way, so that the comparison is exact only where no message exists and no worker writes. audit( pred ), at the level of the audits of Contract.h, checks the predicate of the consumer at such a point: called by one thread where rearm() may be called, it asserts the precondition of rearm() (the outboxes empty, \( C = 0 \) or the mailbox stopped, the inboxes drained), then pred( me ) for each worker, or pred(). The predicate is the consumer's (for the search, that each value equals the minimum over the predecessors, or a Shadow that compares the incremental state with one computed from scratch), so that the mailbox gives the point and not the property; below the level of the audits the call compiles to nothing.
Lemma 13 (the audit at a quiescent point). Let audit() be called at a barrier, after every worker has returned from its last call of the computation and before any makes its first call of the next one. If its precondition holds, the predicate reads the state that the workers left, with no message on its way and none pending in an outbox, and no worker writes while it runs.
Indeed, with the outboxes and the inboxes empty, no message exists: in a channel there is none when \( C = 0 \), by (9), and none after a stop once leftovers() has drained them, which the drain of the precondition checks. The barrier orders every operation of the workers before the call and the call before every operation of the next computation, so that the thread of the audit reads each write of every worker and none races with it; the predicate of the worker \( \mathit{me} \) may then read the state of the others, as the minimum over the predecessors does.