|
ADS
Algorithms and Data Structures
|
The headers of include/ADS/concurrent realize, beyond the book, the structures that several threads change at once without a lock, or with the fewest locks: the queues between producers and consumers, the deque of work stealing, the union-find and the hash tables shared by threads, the relaxed priority queue, the event count on which a thread sleeps until a condition holds, the priority queues of the workers of a search that the idle workers steal from, an exact priority queue without locks, the table of one writer and the board of the least keys of the workers. This page collects what the headers take for granted: the model of the threads and of the memory and the meaning of correct and of nonblocking (see Definitions and notation), the structures and the cost of their operations (see The structures and their costs), and, for each family, the property on which its correctness rests and the argument behind its cost (from Queues of producers and consumers to A board of least keys). The pseudocode of each operation is instead on the page of its header, in the comment of its function, together with the paper that it follows, and with the order of memory of each access to a shared word written as a comment.
A shared object is a structure whose operations are called by several threads, each a sequence of calls; an operation takes time, from its invocation to its response, and two operations of two threads may overlap. A run of the object is linearizable if each operation seems to take effect at one instant between its invocation and its response, its linearization point, so that the responses are those of the sequential object on the operations taken in the order of their points (Herlihy and Wing); an object is linearizable if its runs are, and then a thread may reason on it as on the sequential structure of the other areas. The headers name the point of each operation, e.g., the compare-and-swap that claims a place, or the store that publishes an item.
An implementation is blocking if a thread stopped in the middle of an operation (descheduled, or slow) may keep the others from completing theirs, as a thread that holds a lock does. It is lock-free if, whatever the threads that stop, some thread that keeps running completes an operation in a finite number of its own steps, i.e., the system as a whole makes progress, though a single thread may starve; it is wait-free if every thread that keeps running completes each of its operations in a finite number of its own steps (Herlihy). A loop that retries a compare-and-swap is lock-free, since the compare-and-swap of a thread fails only because that of another one succeeded, but it is not wait-free.
The memory is that of C++, which the headers use through std::atomic (Boehm and Adve). A data race is a pair of accesses of two threads to one location, one of them a write, neither atomic and neither ordered before the other; a program with a data race has no defined meaning, and a shared word is therefore always an atomic. Each atomic access carries an order: a relaxed one is atomic and nothing more; a store with release and a load with acquire that reads its value synchronize, so that every write that the storing thread made before the store happens before every read that the loading thread makes after the load; a sequentially consistent access is acquire and release and, moreover, takes a place in a single total order \( S \) of all such accesses, consistent with the order of each thread. The orders between threads come only from these: a relaxed access orders nothing, and two threads that write and then read two different words with release and acquire may both miss the write of the other, which only \( S \) excludes.
| Symbol | Meaning |
|---|---|
| \( p \) | the number of the threads that use an object |
| \( c \) | the capacity of a bounded queue, a power of 2, so that the index \( i \) is at the place \( i \bmod c \), a mask |
| \( h \), \( t \) | the head and the tail of a queue, or the top and the bottom \( b \) of a deque: integers that only grow, the items being those of \( [ h , t ) \) |
| \( \mathrm{CAS}( x , e , d ) \) | the compare-and-swap: if \( x = e \), then \( x \gets d \) and true, else false (and \( e \gets x \) in the code), one atomic read-modify-write |
| \( S \) | the total order of the sequentially consistent accesses and fences |
| \( \mathit{seen} \) | the copy that a thread keeps of an index written by another one, read again only when the structure looks full or empty |
Two more facts of the hardware decide the costs. A write to a line of cache takes it from the caches of the other cores, which then miss on it; two words written by two threads on one line (false sharing) make the line travel at each write, and the headers put each such word on a line of its own, often on a pair of lines, since the processors of x86 fetch the lines two at a time. A read-modify-write, e.g., a compare-and-swap, costs several times a plain access and orders the memory around it; a structure is fast when its common case has none. Finally, the ABA problem of a compare-and-swap on a pointer: a thread reads the top \( A \) of a stack and its successor \( B \), another thread pops \( A \) and \( B \) and pushes \( A \) again, and the compare-and-swap of the first thread from \( A \) to \( B \) succeeds and puts back on the stack a cell that is no longer there. The headers avoid it by construction rather than by counters: a stack whose cells are only pushed one at a time and taken all at once never compares a pointer read before a pop.
| Structure | Threads | Progress | Cost of an operation |
|---|---|---|---|
| SPSCQueue | one producer, one consumer | wait-free | \( O( 1 ) \), no read-modify-write |
| MPSCQueue | many producers, one consumer | wait-free push but for the allocation of a block, lock-free creation of a producer | \( O( 1 ) \) amortized, no read-modify-write but per block |
| MPSCInbox | many producers, one consumer | lock-free push, wait-free take | one compare-and-swap per push, one exchange per take of \( k \) messages, plus \( O( k ) \) |
| MPMCQueue | many producers, many consumers | lock-free but for a thread stopped between its claim and its publication | one compare-and-swap per operation without contention |
| WorkStealingDeque | one owner, many thieves | wait-free push, lock-free take and steal | \( O( 1 ) \) amortized for the owner, a compare-and-swap only on the last item; one per steal |
| ConcurrentUnionFind | any | lock-free | \( O( \log_{2 + m / n} n ) \) amortized on one thread |
| ConcurrentCuckooTable | any | blocking (a lock per region), lookups without locks for the keys and values read atomically | \( O( 1 ) \) expected, \( O( 1 ) \) amortized for the doublings |
| ConcurrentFlatTable | any | wait-free lookups but across a growth, insertions blocking only during a growth | \( O( 1 ) \) expected, \( O( 1 ) \) amortized for the growths; no removals |
| MultiQueue | any, by a handle each | blocking (a lock per queue, taken only at the first try) | \( O( \log m ) \) amortized on a queue of \( m \) pairs, \( c / ( c - 1 ) \) draws expected; relaxed |
| StealablePriorityQueue | one owner, many thieves | wait-free for the owner, lock-free steal that waits a bounded time for an answer | \( O( \log m ) \) for the owner, no read-modify-write; one exchange per steal, \( O( 1 ) \) or \( O( m ) \) for the answer of the owner |
| LockFreePriorityQueue | any, by a handle each | lock-free but for the allocation of a node; the reclamation by epochs blocking | \( O( \log m ) \) expected per insertion, two compare-and-swaps on average; one fetch-and-or per DeleteMin, plus the prefix walked; exact |
| EventCount | any | a waiter sleeps, a notifier never waits | a fence and a read when nobody waits |
The queues of one producer or of one consumer are cheaper than the general one because each index has a single writer: it is written by plain stores with release and read by loads with acquire, and no read-modify-write is needed, while many writers of one index must agree by a compare-and-swap, and contend on its line. The copies of the indices keep the two threads of SPSCQueue off each other's lines but when the queue looks full or empty, i.e., once per lap rather than once per item. The many producers of MPSCQueue are given one lane each, a queue of one producer and one consumer, so that they never contend, at the price of a consumer that visits the lanes in turn; MPSCInbox is the simplest of the three, one stack, and it suits the messages taken in bursts.
Lemma 1 (the queue of Lamport). Let the producer write the item of the index \( t \) and then store \( t + 1 \) in the tail with release, and let the consumer load the tail with acquire, read the items of the indices below it, and then store the new head with release, which the producer loads with acquire before it reuses a place. Then the consumer reads each item whole, after it was written, and the producer never overwrites an item not yet read:
\[ \mathrm{write}( A[ i ] ) \to \mathrm{read}( A[ i ] ) \to \mathrm{write}( A[ i + c ] ) \quad \forall i , \tag{1} \]
\( \to \) being the order of happening before.
Indeed, the write of \( A[ i ] \) precedes in the producer the release store of a tail \( > i \), which the consumer reads by an acquire load before it reads \( A[ i ] \); the store and the load synchronize, and the first arrow of (1) follows. The second arrow is the same argument on the head, since the producer writes \( A[ i + c ] \) only after it has read a head \( > i \), i.e., \( t - h < c \). The indices only grow and are reduced by the mask, so that the comparisons \( t - h = c \) (full) and \( h = t \) (empty) hold also when the integers wrap around. A stale copy \( \mathit{seen} \) of the index of the other thread is never ahead of it, and therefore only makes the queue look fuller or emptier than it is, never the converse; this is why the copy is read again before the queue is declared full or empty. Each operation runs a constant number of steps, whatever the other thread does, and the queue is wait-free. The linearization point of a push is its store of the tail, and that of a pop its store of the head (or, if it finds the queue empty, its load of the tail).
MPSCQueue applies Lemma 1 to each lane, whose block holds the count of its items in place of the tail; the link to the next block is stored with release after the block is full, and a block goes back to its producer on a stack only after the consumer has read all its items, so that a block is reused only when (1) holds for all its places. In steady state a lane cycles over \( \lceil m / B \rceil + 1 \) blocks for at most \( m \) items held at once, and an item costs one store of the count. The consumer of SPSCQueue and of MPSCQueue waits a few pauses when it is right behind a streaming producer and finds only a few items (B-Queue): it then takes a batch at once, and the lines of the count and of the items travel once per batch instead of once per item, which would slow the producer down several times over.
Lemma 2 (the sequences of Vyukov). In MPMCQueue the place of the index \( i \) holds the sequence \( i \) when it waits for the push of \( i \), \( i + 1 \) when it holds that item, and \( i + c \) when it waits for the push of \( i + c \); a producer claims the index \( p \) by \( \mathrm{CAS}( t , p , p + 1 ) \) only after it has read the sequence \( p \), and publishes by storing \( p + 1 \) with release, and a consumer does the same on the head with \( q + 1 \) and \( q + c \).
The compare-and-swap gives each index to one producer and to one consumer, and the sequence, written with release and read with acquire, carries the order (1) from the producer to the consumer and back. A producer that reads a sequence below \( p \) finds the item of \( p - c \) not yet taken, i.e., the queue full, and one that reads a sequence above \( p \) lost the index to another producer, and reads the tail again. A failure of the compare-and-swap means that another thread claimed the index, hence the queue makes progress; but a thread stopped between its compare-and-swap and its publication holds up the threads that come round to its place, and the queue is lock-free only when no thread stops there.
MPSCInbox pushes cells on a stack of Treiber, by a loop of \( \mathrm{CAS}( \mathit{top} , \mathit{next} , \mathit{cell} ) \), and the consumer takes the whole stack by \( \mathrm{exchange}( \mathit{top} , \textbf{nil} ) \) and reverses it. The ABA problem needs a compare-and-swap whose expected value was read before the cell it names was popped and pushed again; here the only compare-and-swap is that of a push, whose expected value is the top read by the pusher and whose new cell is its own, and a cell is never popped alone, so that a success always links the new cell above the true top (a cell used again, once its block came back to its producer, is pushed as a new one, and the push reads nothing of the cell it expects). The same argument holds for the stacks of the lanes of MPSCQueue and of the returns of ConcurrentPoolResource.
The deque of Chase and Lev serves the scheduling by work stealing: each worker pushes and takes its tasks at the bottom of its own deque, as on a stack, which keeps the tasks it made last, and their data, in its cache, and an idle worker steals the oldest task at the top of the deque of another, which is often the root of a large subtree of work. The owner writes the bottom \( b \) alone; the top \( t \) only grows, by a compare-and-swap of the thieves or of the owner, and the items are those of \( [ t , b ) \).
Lemma 3 (the last item). Let take() store \( b - 1 \) in the bottom and then load the top, and steal() load the top and then the bottom, all four accesses sequentially consistent. Then, when one item is left, the owner and a thief do not both take it, and they do not both leave it.
In fact, the four accesses lie in \( S \). If the load of the bottom of the thief follows in \( S \) the store of the owner, the thief sees \( t \ge b \) and gives up, or both race for the item by a compare-and-swap of \( t \) from the same value, which only one wins; otherwise the load of the top of the owner follows the load of the thief, and in either case the owner sees a top that tells it whether to race. With release and acquire alone both threads could read the old value of the word written by the other and both take the item; this is the reason of the two fences of Lê et al., written in the code as sequentially consistent accesses, which the sanitizer of threads models. All other items are taken by one side only, since a thief takes \( t \) and the owner \( b - 1 \), distinct when more than one item is left.
A full vector is doubled by the owner, which copies the items of \( [ t , b ) \) to their indices in a vector of twice the places and publishes it with release; a thief that read the old vector reads from it an item that the copy did not change, and the old vectors are kept until the deque dies, so that no read is ever of freed memory. Their sizes form a geometric series, below the size of the last vector, and the doublings cost \( O( 1 ) \) amortized per push, as in the vector of section 4.3.
ConcurrentUnionFind keeps a forest of parents, each an atomic word, and changes it only by compare-and-swap (Jayanti and Tarjan).
Lemma 4 (linking by index). If a root \( x \) is hooked only under a root \( y < x \), by \( \mathrm{CAS}( p[ x ] , x , y ) \), and a parent \( p[ x ] \) is otherwise only replaced by an ancestor of \( x \), then at every moment
\[ p[ x ] \le x \quad \forall x , \tag{2} \]
the forest has no cycle, and the root of each tree is its least element.
By induction on the steps: a hook succeeds only if \( x \) is still a root, and sets \( p[ x ] = y < x \); the splitting of find() replaces \( p[ x ] = u \) by \( p[ u ] \le u \), by a compare-and-swap that fails if \( p[ x ] \) changed meanwhile, so that the new parent is an ancestor and (2) still holds. Along a path the elements decrease strictly, which excludes a cycle and makes the root the least element; hence the label of a set does not depend on the order of the operations. A failed compare-and-swap of a splitting is harmless, since it only leaves a longer path, and a failed hook means that another thread hooked \( x \) first, which is progress; unite() then finds the roots again. The operations are linearizable: unite() at its successful hook, find() at the read that finds a root, and sameSet() at the second find() when the root of \( x \) is still a root then. On one thread the linking by index with the splitting costs \( O( \log_{2 + m / n} n ) \) amortized per operation on \( m \) operations and \( n \) elements (Tarjan and van Leeuwen); the randomized linking of Jayanti and Tarjan has a better bound on \( p \) threads, at the price of labels that are not the least elements.
ConcurrentCuckooTable is the cuckoo hashing of BucketCuckooTable (see the theory of dictionaries), with a lock, a counter of versions, per region of buckets; both buckets of a key, and every bucket of the cuckoo path of an insertion, lie in the region of the key, so that an operation on one key takes one lock. Three arguments make it correct.
First, no deadlock. The operations that take more than one lock (the doubling, reserve(), clear(), forEach(), consistent()) take all those in use in increasing order, and a thread that holds the lock \( i \) and waits for \( j \) has \( i < j \); a cycle of waits would give \( i_1 < i_2 < \cdots < i_k < i_1 \), which is impossible.
Second, the lookups without locks (a seqlock). A reader loads the version \( v \) with acquire, gives up if it is odd (a writer holds the lock), reads the tags and the places with atomic loads that acquire, and loads the version again: if it is still \( v \), no writer held the lock in between, and what it read is a state of the region. A writer makes the version odd by a compare-and-swap and then stores with release, so that a reader that reads one of those stores synchronizes with it, the compare-and-swap happens before its second load of the version, which reads the odd version or a later one, and the reader tries again (Boehm, who places instead a release fence after the compare-and-swap and an acquire fence before the second load, with relaxed accesses between; the two forms give the same order, the sanitizer of threads models only the first, and on x86-64 both are plain loads and stores). No access is a data race, since all of them are atomic. A lookup of an absent key may return before the version: each bucket has bits of overflow, one of which is set before a key enters its other bucket, by an insertion or by a move that then clears its tag in the first bucket by a release (the remap entries of Breslow et al., as bits). A key whose tag is not among the tags of its first bucket, read with acquire, and whose bit is clear, read after them, is then in neither bucket at the moment of that read, if the table is still in use; the bits are cleared only in a table not yet in use or by clear(), after the tags.
Third, the doubling. A region whose load would pass 0.98, or an insertion that finds no cuckoo path of at most 5 moves among 1024 buckets, doubles the table under all the locks, the threads that wait for a lock migrating parts of whole regions with the thread that doubles, since the pairs of the old buckets \( [ l , h ) \) go to the new buckets \( [ 2 l , 2 h ) \) and to no others (Maier, Sanders and Dementiev); the tables replaced stay alive while a reader may be on one, and with sizes that double they occupy less than the table in use. With 2 buckets of 4 places, \( n \) random keys fit with high probability while \( n < 0.9803 \cdot 4 B \), the threshold of the 4-orientability of the random graphs (Cain, Sanders and Wormald), and a search in breadth over \( M \) places finds a path of \( O( \log_4 M ) \) moves, against the \( M / 2 \) of a search in depth (Li et al.). A lookup touches two buckets, i.e., \( O( 1 ) \) lines, and an insertion \( O( 1 ) \) expected moves, the doublings adding \( O( 1 ) \) amortized; with uniform keys two operations contend for a lock with probability \( 1 / P \) for \( P \) regions.
ConcurrentFlatTable gives up what ConcurrentCuckooTable needs its versions for: a word, once written, never changes nor moves within its vector, since there are no removals and the keys are never displaced. The vector holds \( 2^l \) atomic words, each 0 or a pair (or the index of the node of a pair), and the key of hash \( h \) is looked for from the place \( \lfloor h / 2^{64 - l} \rfloor \) on, cyclically, up to its word or to a word 0; an insertion writes the first word 0 of that sequence by \( \mathrm{CAS}( W[ i ] , 0 , w ) \), and on a failure reads the word that another thread wrote there before it goes on. This is the folklore table that Maier, Sanders and Dementiev found the fastest of the tables shared by threads, with the growth and the nodes added.
When the pairs lie in the words, each place has besides a tag, 0 or 7 bits of the hash of its key with the high bit set, in a vector of bytes apart (the pairs in nodes have none, as a tag would add a miss to the two of a key found in a node), so that a lookup reads the tags of 8 places in one word and compares them with its own at once, reading the word of a place only when its tag matches; a key that is absent costs one line of the tags, \( 1/8 \) of the words or less, as in the tables with metadata of Swiss and F14 kind. A tag is written, with release, after the word it tags, and always with the same value, by the insertion that wrote the word or by any insertion that passes the place while it looks for its own; an insertion takes effect when the tag of its word is written.
Lemma 5 (the lookups without locks). Let the words and the tags of a vector be written only from 0, once each, and only while it is in use, let an insertion write the tags of the places it passes before it writes its own, and let a lookup of \( k \) in the vector \( T \) read the tag 0 at the place \( j \), after tags at the places from that of \( k \) to \( j - 1 \) whose words hold other keys, and then find \( T \) still in use. Then no insertion of \( k \) had taken effect when the lookup read the tag of \( j \).
Indeed, an insertion of \( k \) writes the first word 0 of the sequence of \( k \), and before its own tag the tags of all the places it passed; had it taken effect, the place \( j \), which comes before its word or is its word, would have had its tag when the lookup read it, since a tag written stays. A lookup that finds \( k \) returns a pair that stays, and is linearized at the read of its word; one that finds the vector replaced starts over on the new one, which happens once per growth. The lookups read with acquire, so that the word of a tag read, and the pair of a node, built before the compare-and-swap with release that published its index, are read whole; they write nothing, and \( p \) threads that only read scale as \( p \) independent sequential tables. An insertion that finds \( k \) in a word whose tag is still 0 writes the tag before it answers, so that its answer, the key there, comes after the insertion has taken effect. For the pairs in nodes, which have no tags, the lemma holds with the words in place of the tags, an insertion taking effect at its compare-and-swap.
Lemma 6 (no insertion into a vector being copied). Let a writer raise its counter and then read the flag \( g \), and the thread that grows the table raise \( g \) and then read the counters, all these accesses sequentially consistent, and let a writer that reads \( g \) raised lower its counter and retry after the growth. Then no word of a vector is written once its copy has begun.
The four accesses lie in the single order \( S \): if the read of \( g \) by the writer follows the raise of \( g \), the writer backs off; otherwise its raise of the counter precedes the read of the counters by the grower, which waits for it to drop, i.e., for the writer to leave the vector (the mutual exclusion of Dekker, which Dijkstra published). The copy reads each word of the old vector once and writes it at the first free place of its sequence in the new one, which nobody else reads yet; the new vector is published, with release, after all its blocks of 4096 words are copied, and the threads that come to insert meanwhile copy blocks instead of waiting. With the load kept at most \( 1 / 2 \), a lookup reads on average \( \frac{1}{2} ( 1 + 1 / ( 1 - \alpha ) ) \le 1.5 \) words when it succeeds and \( \frac{1}{2} ( 1 + 1 / ( 1 - \alpha )^2 ) \le 2.5 \) when it fails, at the load \( \alpha \) and with random hashes (Knuth), most of them on one line of 8 words; the copies of the growths cost \( O( 1 ) \) amortized per insertion, since the sizes double. An insertion is blocking only during a growth, and the lookups never are.
A key and a value of 8 bytes each do not fit one word, and the pair of a node costs a second miss of the cache on each lookup that finds its key. Where the processor writes 16 bytes by one compare-and-swap without locks, a place is instead two words, the key and the value, written from \( ( 0 , 0 ) \) by that instruction (the folklore table of Maier et al.), and Lemma 5 holds unchanged for the key: a lookup that reads the key with acquire and then the value reads a value written with that key, or a later one of update(), which changes the value by the same instruction and never the key. The copy of a growth moves the two words at once, and the places of a vector are twice as many words, all on the line of their key.
A table cleared often and filled little in between (the restarts of an incremental search) pays at each clear() the capacity of its vector. With the policy EpochClear each group of 8 places has a stamp, and the group is in use only if its stamp is the epoch of the table, which clear() raises in \( O( 1 ) \): a lookup takes a group out of use as free, and an insertion that reaches one renews it, taking it by a compare-and-swap of its stamp to a mark, writing 0 to its words and tags, and storing the epoch with release. The other insertions there wait for the store, while the lookups see the group free, which is right since no insertion of the new epoch has taken effect in it; once stamped, the group is that of a new vector, and Lemma 5 holds for it unchanged. The renewal runs within the critical section of an insertion, so that no growth runs with it (Lemma 6), and a growth copies only the groups in use. When the epoch would reach the mark, the largest stamp, clear() writes the whole vector and starts again from 1, once per \( 2^{|S|} - 2 \) clears for stamps of \( |S| \) bits, so that no old stamp equals a new epoch.
A priority queue shared by \( p \) threads under one lock serializes them, and even the exact queue with the best combining serves one operation at a time. A relaxed priority queue returns instead a pair that need not be the least: the rank of a popped pair is 1 plus the number of the pairs present with a smaller key, and its rank error the rank less 1, 0 for an exact queue. A search that takes its states from a relaxed OPEN expands a few states that an exact one would not, and in exchange its threads do not wait for one another.
The MultiQueue keeps \( n \) sequential queues, each under its own lock: a push puts the pair in a random queue, and a pop takes the least pair of the better of two random queues. With \( n = c p \) queues, at most \( p - 1 \) held by other threads, a queue drawn at random is held with probability less than \( 1 / c \), and a lock is taken at the first try or after a new draw, in at most \( c / ( c - 1 ) \) draws on average, 2 for the default \( c = 2 \), with no thread that waits for a lock.
Theorem 7 (Walzer and Williams). Let the pairs be spread over \( n \) queues uniformly at random, and then popped one at a time, each from the queue whose least key is the \( j \)-th of the \( n \) with a probability \( \sigma_j \), where the sums \( \sigma_{\le i} = \sigma_1 + \cdots + \sigma_i \) satisfy \( \sigma_{\le i} > i / n \) for \( i < n \). The rank error of a pop converges in distribution as the pops go on, and the mean of its limit is
\[ E[ R ] = \sum_{i=1}^{n-1} \frac{\sigma_{\le i} ( 1 - \sigma_{\le i} )} {\sigma_{\le i} - i / n} ; \tag{3} \]
for the better of two queues drawn with replacement, \( \sigma_{\le i} = 1 - ( 1 - i / n )^2 \) and
\[ E[ R ] = \sum_{i=1}^{n-1} \left( 2 - \frac{i}{n} \right) \left( 1 - \frac{i}{n} \right) = \frac{5}{6} n - 1 + \frac{1}{6 n} , \tag{4} \]
and the maximum over \( \mathrm{poly}( n ) \) pops is \( O( n \log n ) \) with high probability.
The argument is about the queues ordered by their least keys. The \( i \) best queues hold, of the pairs that come next in the order of the keys, a share \( i / n \), since the pairs were spread at random, and a pop takes from them with the probability \( \sigma_{\le i} \); when \( \sigma_{\le i} > i / n \) they are emptied faster than their share, and the number of pairs that separate the \( i \)-th least key from the \( ( i + 1 ) \)-th is a geometric variable whose mean depends only on \( \sigma_{\le i} \) and \( i / n \); Walzer and Williams prove that the ranks of the least keys of the queues converge to sums of such independent variables, whence (3). With one draw, \( \sigma_{\le i} = i / n \), the best queues are emptied only as fast as they are filled, and the rank error grows without bound; two draws that fall on the same queue are such a draw, and MultiQueue draws two distinct queues instead, for which \( \sigma_{\le i} = 1 - ( n - i ) ( n - i - 1 ) / ( n ( n - 1 ) ) \) and \( \sigma_{\le i} - i / n = i ( n - i ) / ( n ( n - 1 ) ) \), so that (3) becomes
\[ E[ R ] = \sum_{i=1}^{n-1} \sigma_{\le i} \, \frac{n - i - 1}{i} , \tag{5} \]
a little less than (4): 4.63 against 5.69 for \( n = 8 \), 24.53 against 25.67 for \( n = 32 \). The earlier bounds of Alistarh et al., \( O( n ) \) for the mean and \( O( n \log n ) \) for the maximum, hold for pushes and pops mixed as well, but for a comparison and a pop done atomically; as Williams, Sanders and Dementiev, MultiQueue reads the least keys of the two queues without their locks, possibly stale, and in a run of many threads its rank errors are measured rather than bounded.
Lemma 8 (the buffers). In each queue, let the deletion buffer \( D \) be empty only if the queue is, and let no pair of the insertion buffer \( I \) or of the heap \( H \) be less than one of \( D \). Then the least pair of \( D \) is the least of the queue, and the push and the pop of MultiQueue::Handle keep both properties.
The first statement is the second property. A push of a pair less than the greatest of \( D \) puts it into \( D \), moving the greatest of a full \( D \) into \( I \), which is not less than the rest of \( D \); a greater pair goes into \( I \), or into \( D \) when \( I \) and \( H \) are empty; and the pairs of a full \( I \) go into \( H \), which changes neither property. A pop takes the least of \( D \) and, if \( D \) becomes empty, moves \( I \) into \( H \) and the least pairs of \( H \) into \( D \). Each queue is therefore exact, the relaxation is only in the choice of the queue, and Theorem 7 applies unchanged; the heap is touched by batches of 16 pairs, which costs \( O( \log m ) \) amortized per operation on a queue of \( m \) pairs and keeps the lines of \( D \) and \( I \) in the cache of the thread. The stickiness of Williams, Sanders and Dementiev, the two queues kept for \( s \) operations, saves more misses; it has no theory yet, and their measures show rank errors that grow about linearly in \( s \).
The lemma asks of \( H \) only an exact queue, and MultiQueue takes it as a template: with the keys of packFG(), the pairs \( ( f , g ) \) of a best-first search with integer costs, \( H \) can be the bucket queue of BucketHeap, whose pushes and pops take \( O( 1 ) \) amortized time with bounded keys, so that the cost of an operation no longer grows with \( m \). The Multi Bucket Queue of Zhang, Posluns and Jeffrey shares the buckets among the threads, each bucket a MultiQueue of its own; here each queue keeps its buckets under its lock, and the choice of the queue is the one of Theorem 7.
A pop that finds both queues empty scans all the queues, each under its lock: when no push runs at the same time, a scan that finds nothing proves the structure empty, which a parallel search needs to stop.
A thread that waits for an item could look again and again, which wastes a core, or sleep for fixed lengths, which delays the item. The event count of Reed and Kanodia lets it sleep until another thread signals that the condition may have become true, with no lock and with nearly no cost for the signal when nobody sleeps. A waiter announces itself and reads the epoch \( e \) in one read-modify-write, looks at the condition once more, and sleeps while the epoch is \( e \); a notifier makes the condition true, issues a fence, reads the number of the waiters, and only if it is positive advances the epoch and wakes them.
Lemma 9 (no lost wake-up). Let the read-modify-write of the waiter be followed by a full fence, and the write that makes the condition true be followed by a full fence before the notifier reads the waiters. Then a waiter does not sleep through a notification of a condition that is true.
Indeed, the two fences lie in \( S \). If that of the notifier comes first, the waiter, looking at the condition after its own fence, sees it true and does not sleep; if that of the waiter comes first, the notifier reads its announcement and advances the epoch, and the waiter either has not yet compared the epoch, and sees the new one, or sleeps on \( e \) and is woken. A notification with nobody waiting costs the fence and the read of a line that stays shared; with ADS_EVENTCOUNT_RMW the notifier reads the waiters by a read-modify-write instead of the two fences, which reads the last value in the order of the modifications of the word and so either sees the waiter or is seen by it through the release sequence; it is the form taken under the sanitizer of threads, which does not model the fences, when the build defines ADS_SANITIZE_THREAD.
Before it sleeps, a waiter may spin for a while, since a condition that becomes true within a few microseconds costs no system call then; the spinning itself is not free, as the loads and the failed compare-and-swaps of the threads that spin on one line keep moving it between their caches. The exponential backoff of Anderson (Backoff.h) runs \( 2^k \) pauses of the processor before the look \( k + 1 \), up to a bound \( S \), and from then on yields the processor to the system at each look: after \( k \) looks a waiter has spun \( 2^{k+1} - 1 \) pauses, so that the looks of \( p \) threads at one line thin out geometrically while the delay added to a wait of length \( t \) is less than \( t \) (the last doubling at most doubles it), and a wait longer than \( 2^{S+1} \) pauses gives the processor back. spinning() tells when the spinning is over, which is the time to move to the event count above.
A best-first search on \( p \) workers (a branch-and-bound by bounds, an A* search) may keep its OPEN in one queue shared by all, exact under a lock or relaxed as the MultiQueue (see Relaxed priority queues), or in a queue per worker, from which the idle workers steal. The second keeps the order of each worker exact, which a search needs when it counts the nodes of each worker against a limit, or when it wants the same run from the same steals; it loses the global order, and a worker may expand a node worse than the best of another, a loss that the steals keep small when they move good nodes. StealablePriorityQueue is such a queue, and StealingFrontier the \( p \) of them with the termination; the choices are three: how many pairs a thief takes, which ones, and at what price for the owner.
How many. Half of them, as in the queues of Hendler and Shavit and in the priority queues stolen by Wimmer et al.: a steal of one pair sends the thief back at once, while a steal of half spreads the pairs made by one worker over \( p \) workers in about \( \log_2 p \) rounds of steals. The Stealing Multi-Queue of Postnikova et al. steals instead a batch of a few of the best tasks, which its owner sets apart in a buffer and skips in the meantime, so that the order of its owner is relaxed by that buffer.
Which ones. The better half sends the victim, which made those pairs, to worse ones, and the next steal brings the good pairs back the other way; the worse half gives the thief the pairs that a best-first search expands last, and that a bound improved in the meantime is likely to prune. An interleaved half gives each worker a share of the best pairs as of the others: the balancing of Tschöke, Lüling and Monien is best when each of the \( p \) processors holds one of the \( p \) subproblems of least bound, and so balances the least bounds of the heaps besides their sizes, Karp and Zhang send each child to a random processor, and the randomized priority queue of Sanders spreads its items at random over the processors, for the same reason. The queue deals its pairs to two heaps \( H_0 \) and \( H_1 \) (a push into the smaller one, into each in turn when they are as large), so that the pairs pushed one after the other, e.g., the children of a node, go to both, and either heap holds, for every range of keys, about half of the pairs in it; a thief takes the heap whose least pair is not the least of the queue, so that the owner keeps its best pair and its next pop.
At what price. A queue whose pairs a thief may take at any time makes its owner race the thieves at each pop, and by the laws of order of Attiya et al. a linearizable pop of such an object needs a read-modify-write or a fence, as the take() of the deque of Chase and Lev (Lemma 3). The heaps of StealablePriorityQueue are instead read by their owner alone: a thief raises the flag hungry of the queue, which the owner reads with no order at its next push or pop (or at serve()), and the owner answers by moving a heap into the offer, an atomic pointer published with release, which a thief claims by an exchange with null, the receiver-initiated steals of the private deques of Acar, Charguéraud and Rainey. The common case of the owner costs so no read-modify-write and no fence, and a thief waits for the next operation of the owner, a few microseconds of spinning at most before it tries another victim.
Lemma 10 (the order of the owner). Let the owner take the offer back, by an exchange with null, before a pop whose two heaps are empty or whose least key is greater than the least key \( k_O \) of the offer. Then each pop of the owner returns a pair of least key among those that the owner holds at the moment of the pop, the pairs of an offer not yet claimed included.
Indeed, the heaps of the owner change only by its own operations, and the offer, once published, does not change until one exchange takes it: a thief or the owner, never both, since the exchanges on one word are totally ordered and only the first finds the pointer. If the least local key is not greater than \( k_O \), the local pair is a least pair of all, whether a thief claims the offer before the pop or not; otherwise the owner exchanges, and either it gets the offer back and pops from the pairs joined, or a thief had claimed it before, and the pairs were no longer of the owner when it popped. Each pop is thus exact at the moment of its exchange, or of its last change of the heaps; the only pairs that leave the owner otherwise are those of an offer, which is a choice of the owner that keeps its least pair.
Lemma 11 (the end of the search). In StealingFrontier, let the counter \( C \) start at \( p \), let a worker subtract 1 when its pop finds its heaps and its offer empty, and a thief add 1 before the exchange that claims an offer and subtract 1 if the exchange fails, and let only a worker that holds a pair (or the program before the run) push. Then no pair exists when \( C = 0 \), and none exists afterwards.
Every pair is in the heaps or in the offer of a worker that has not left \( C \), since a worker leaves only with nothing, or in the offer claimed by a thief, which entered \( C \) before its exchange. The victim that finds its offer claimed has read the null of the exchange of the thief, an exchange with release read by one with acquire, so that the entry of the thief happens before the exit of the victim, and \( C \), totally ordered by its modifications, cannot reach 0 in between; a pair in transit is therefore always counted. When \( C = 0 \) no pair exists, and no pair can be created, since only a worker that holds one pushes; the thieves that still try enter and leave \( C \) with nothing to find, and see \( C = 0 \) again.
The costs, for \( m \) pairs: a push and a pop \( O( \log m ) \) on a 4-ary heap of about \( m / 2 \) pairs, half as deep in levels of the binary heap, plus a load of the flag; the answer to a thief \( O( 1 ) \), the store of a pointer, unless the two heaps differ by more than a factor of 4 (the heap left after a steal, before the pushes refill the other), when the owner deals all its pairs again to two heaps in \( O( m ) \); the steal one exchange for the thief and the deal of the \( s \) pairs taken to its own two heaps, \( O( s ) \), by the heap construction of Floyd. A pair is copied only by a deal; the pairs of an offer move with their heap, by its pointer.
The bounds. A branch-and-bound selects its nodes by one key (the bound itself for best first, the depth for depth first, an estimate for best estimate, with the order of the pushes as the tie) and prunes by another one, the bound: when the least bound \( \beta \) of the nodes that a worker holds cannot improve the incumbent beyond the tolerance, the whole queue is dropped, and the choice to dive compares the children with \( \beta \). With a type of bounds, each pair of the queue carries its bound, and minBound() gives \( \beta \) over the pairs of the owner, as IndexedHeapPair does for the ids of one thread. Each heap keeps its least bound as long as no pop takes a pair of that bound (a push lowers it, if its bound is less), and finds it again by a scan of its pairs when one does. With bounds independent of the keys, a pop takes the least of \( m \) bounds with probability about \( 1 / m \), and the scans cost \( O( 1 ) \) expected per pop; with bounds that go with the keys, as in a search by best first, each pop takes it, and the scans \( \Theta( m ) \) each. When the pairs scanned exceed 16 times the pops and the pairs held, plus \( 2^{16} \) for the start, on a heap of 64 pairs at least, the heap keeps instead, in a vector apart, the least bound \( \mu( i ) \) of the pairs of the subtree of each node \( i \):
\[ \mu( i ) = \min\{ b( i ) , \mu( 4 i + 1 ) , \ldots , \mu( 4 i + 4 ) \} , \tag{6} \]
\( b( i ) \) the bound of the pair of \( i \) and the children that do not exist left out, so that the least bound of the heap is \( \mu( 0 ) \). A push moves the hole of a new leaf up to the place \( i \) of the new pair: the nodes passed by the hole took the pair of their parent, and get (6) again from their children, the leaf up; the subtree of \( i \) and of each node above it gained the new bound \( b \) alone, and \( \mu \) is lowered to \( b \) from \( i \) up as long as \( b \) is less, since \( \mu \) does not increase toward the root. A pop moves the last pair \( z \) down from the root along a path \( P \); a node off \( P \) on the path of the old last leaf lost \( z \) alone, and keeps its \( \mu \), as all those above it off \( P \), if \( \mu \) is less than the bound of \( z \); the rest of that path, and then \( P \) from its end up, get (6) again. The cost is \( O( \log m ) \) per operation and \( O( 1 ) \) for \( \mu( 0 ) \). The two alternatives cost more on both kinds of bounds: the bounds of the pushes and those of the pops in two multisets, the least bound being the least of the first once their equal tops are taken out, add a push into one of them per operation, on heaps that grow with the pops until they are made again, and a heap by the bounds indexed by the places of the pairs adds a second sift per operation and an update of the index at each move of a pair.
Lemma 12 (the least bound of the owner). Let the owner keep, when it makes an offer, the least bound \( b_O \) of the heap that it moves into the offer, and let minBound() return the least of the least bounds of its heaps that are not empty and, if the offer that it made is still there at an acquire load of the pointer, of \( b_O \). Then the value returned is the least bound of the pairs that the owner holds at the moment of that load.
Indeed, the heaps of the owner change only by its own operations, and the least bound of each is exact: the one known stays the least while no pop takes a pair of that bound and a push lowers it when its bound is less, a scan computes it, and by (6) \( \mu( 0 ) \) is it. The pairs of an offer are fixed from its publication until an exchange takes it, and \( b_O \) is their least bound; at the load, the offer is either still there, and then its pairs are of the owner (Lemma 10: a thief that claims it afterwards takes pairs that the owner held at the load), or claimed, and then its pairs belong to the thief from its exchange on, and are not the owner's any more. The pairs stolen keep their keys and their bounds, since the thief adopts the heap as it is and deals its pairs to two heaps of its own, rebuilding (6) on them; drain() takes the offer back first, if no thief has claimed it, and empties both heaps, so that a queue pruned by its \( \beta \) holds nothing afterwards.
A search that wants one OPEN shared by all its threads in the exact order of the keys (e.g., SPA* of Burns et al.) cannot use the MultiQueue (see Relaxed priority queues), and a heap under one lock serializes its threads. The skiplist of Lindén and Jonsson is linearizable and lock-free, and its DeleteMin pays one read-modify-write in the common case: the pointer of level 0 of a node \( p \) carries in its lowest bit the mark \( d( p ) \), which tells that the node after \( p \) is deleted, so that an insertion, which swings the pointer by a compare-and-swap from its value unmarked, never links a node in front of a deleted one, and the deleted nodes stay in the list as a prefix, to be cut off in batches by one compare-and-swap on the head when a DeleteMin walked more than \( b \) of them. The keys are made distinct by a stamp of the insertion, \( \kappa = ( k , s ) \), and \( x \prec y \) means that \( x \) comes before \( y \) in the list of level 0.
Lemma 13 (the list of level 0). The words of level 0 change only by the compare-and-swap of an insertion, which links a node between two adjacent ones, by the fetch-and-or of a DeleteMin, which sets a mark, and by the cut, which moves the word of the head forward, marked. Hence \( \prec \) is fixed, the deleted nodes are a prefix of the list, the word of the head is marked after the first deletion, and the nodes not deleted have increasing \( \kappa \).
Indeed, a fetch-and-or marks the word of the head or of a node reached by a marked word, and an insertion succeeds only on an unmarked word, whose node \( S_0 \) is then not deleted, with a greater key, while its predecessor is the head, a deleted node, or a node of smaller key.
The upper lists are shortcuts, and need not hold every node, but every pointer must lead forward in \( \prec \). Lindén and Jonsson stop an insertion at the level \( i \) when the successor \( S_i \) is deleted, which they detect by \( d( S_i ) \) or, for the last deleted node, by comparing it with the last deleted node met by the walk of level 0; that walk, however, starts from \( P_1 \), and misses \( S_i \) when the list of level 1 has a branch past which \( P_1 \) lies (a node linked after a node already cut off), and the node would then be linked backwards. The queue tests instead the successor \( f \) of \( S_i \).
Lemma 14 (no pointer backwards). Let \( n \) be linked at level 0 and \( c \) its successor found at an upper level. If the word of \( c \) is not marked, \( f \ne n \), and \( f \) is the tail or \( \kappa( f ) > \kappa( n ) \), then \( n \prec c \); hence every pointer of every level leads forward.
Indeed, if \( c \prec n \), then \( c \) precedes the predecessor \( P_0 \) of \( n \) and has a key not less than \( \kappa( n ) \), and therefore it is deleted (a node not deleted before \( P_0 \) has a smaller key, by Lemma 13); if its word is not marked, \( c \) is the last deleted node, \( n \) is not deleted, and \( f \) is the first node not deleted, either \( n \) or a node before it of a smaller key. The other upper pointer written, that of \( P_i \) to \( n \), leads forward since the walk moves forward and \( P_i \preceq P_0 \prec n \).
Lemma 15 (linearizability). With the abstract queue the pairs of the nodes not deleted in the order of level 0, insert() takes effect at the compare-and-swap that links its node at level 0, tryDeleteMin() at the fetch-and-or that finds unmarked the word of the node it returns, or at the read of a pointer to the tail from the head or from a deleted node when it returns nothing, and tryMinKey() at the read of the first unmarked word.
Indeed, by Lemma 13 the node reached by the first unmarked word is the least of the abstract queue, only one fetch-and-or finds that word unmarked, and no word that does not reach the tail comes to reach it, so that no fetch-and-or marks the tail.
Lemma 16 (the reclamation). Let a cut move the head from \( o \) to \( \nu \). The cuts and their restructures run one at a time (the bit 1 of the word of the head, held by the thread of the cut); no node being inserted lies before \( \nu \); after the restructure every word of the head reaches \( \nu \) or a node after it, ever after; and a node cut off, stamped with the epoch \( r \) read after the restructure, is freed only when no thread that may hold a pointer to it is inside an operation.
Indeed, the DeleteMin of the cut visited each node from \( o \) to \( \nu \) and read its flag of insertion clear, but for \( \nu \); every node before \( \nu \) has its successor deleted, and the restructure, alone, writes each upper word of the head to a node whose successor is not deleted, read after the cut, or leaves it on such a node; the insertions write to the head only nodes being inserted. A thread that reaches a node cut off read a word older than the last compare-and-swap of the cut and of its restructure (otherwise its reads see their words, and by Lemma 14 lead to no node cut); the announce of its epoch is a sequentially consistent exchange and its reads of the words are sequentially consistent, so that the stale read precedes that compare-and-swap in the total order \( S \) of the sequentially consistent operations, being coherence-ordered before it, and the announce, sequenced before the read, precedes it too. Hence the thread announced an epoch \( a \le r \), which the scan that would raise the epoch from \( r + 1 \) to \( r + 2 \), later in \( S \), reads (or a later value of the record); the node waits for the epoch \( r + 2 \). A relaxed announce followed by a full fence, with reads that acquire, gives the same order through the fence, but the sanitizer of threads does not model the fences, and on x86-64 the exchange is one instruction where the store and the fence are two.
Lemma 17 (lock-freedom and the prefix). The operations are lock-free but for the allocation of a node, and in a run of one thread a DeleteMin walks at most \( b + 1 \) nodes and the list holds at most \( b \) deleted nodes between two operations.
Indeed, each operation completes after at most \( L + 2 \) successful read-modify-writes of its own; if none completed after some moment, the finitely many operations running would make finitely many successful ones, after which no word changes, no compare-and-swap fails and no walk is longer than the list, a contradiction. With one thread, a DeleteMin that finds \( j \) deleted nodes walks \( j + 1 \) nodes and leaves \( j + 1 \), or 1 after a cut when \( j + 1 > b \). A thread stopped inside an insertion or inside a cut keeps the head where it is, and the prefix then grows with the deletions; the epochs are blocking in the same way, since a thread stopped inside an operation keeps the nodes cut off afterwards from being freed.
A table that only its owner fills, while the others read it (the CLOSED set of a worker of a search, read by the others to prune their states), needs none of the protocol of Lemma 6: SingleWriterFlatTable keeps the linear probing of ConcurrentFlatTable with the pairs in the words, one word for a set and two for a key and a value, and makes every write by the one writer, by loads and stores and no read-modify-write. An insertion reads the words from the place of its key, stores at the first free one the value (relaxed) and then the key with release; a growth fills a vector twice as large while no reader can see it and then stores it as the vector in use with release; a lookup reads the vector in use and the words with acquire, and, if it ends at a free place, reads the vector in use again, starting over on the new one if it changed.
Lemma 18 (one writer). Let one thread make all the insertions, the updates and the growths of the table, the writes as above, and let any thread make lookups. Then (i) a lookup that reads a key word \( w \ne 0 \) reads with it the value stored at its insertion or a later one, and everything that the writer wrote before the insertion; (ii) a lookup of \( k \) that reads a free place in the vector \( T \) (or a group out of use, with EpochClear) and then \( T \) again as the vector in use is linearized at the read of that place, which no insertion of \( k \) happens before; (iii) a vector replaced is no longer written, and holds every pair inserted before it was replaced, so that a lookup on it reads a table that only lacks the later pairs.
For (i), the store of the value and every write of the writer before the insertion are sequenced before the store of the key with release, which the read with acquire of the key synchronizes with; an update stores the value with release, so that the value read is that of the insertion or of an update, whole, since each is one atomic word. For (ii), let the insertion of \( k \) into \( T \) write the place \( j \): the writer found the places from that of \( k \) up to \( j - 1 \) full (renewing, with EpochClear, each group out of use among them, i.e., writing its words 0 and then its stamp with release), so that their writes are sequenced before the store of \( k \). Were that store to happen before the lookup's read of the place \( i < j \) of the sequence, the write of \( i \) (or of the stamp of its group) would happen before it too, and by the coherence of the reads the lookup would read it, not the free place; were \( k \) inserted instead into a later vector, its store would follow the publication of that vector, and if it happened before the read of \( i \) it would happen before the second read of the vector in use, which would then not read \( T \). For (iii), the writer writes only the vector in use, the new one before it is published, and the copy reads every pair of the old one; the vectors replaced are freed only by clear() or the destruction, with no reader. Hence the lookups never wait, start over at most once per growth, and are wait-free between two growths, while an insertion costs the loads of its probe, one or two stores and no read-modify-write, against the two sequentially consistent ones of the counter of a thread in ConcurrentFlatTable.
The single writer may hand its role over to another thread by any synchronization (a join, a barrier, a release with an acquire), since the writes are then ordered as those of one thread; clear(), which frees the vectors replaced, needs every reader gone, as in ConcurrentFlatTable.
MinBoard keeps \( p \) keys, one per thread, each in an atomic word on a line of cache of its own, written only by its owner by publish( i , k ) and read by all by min(), the least of the slots; every access is relaxed. The board orders nothing but each slot by itself, and this is what it guarantees.
Lemma 19 (the coherence of the board). Let each slot be written by its owner only. Then (i) a read of the slot \( i \) reads one of the keys published there (or the initial one), not older in the order of the publishes of \( i \) than any publish of \( i \) that happens before the read, and two reads of \( i \) by one thread read the second no older than the first; (ii) min() returns \( \min_i x_i \) of keys \( x_i \) so read, one per slot; (iii) if the keys published in each slot never increase, the value returned lies between the least key of the board after the last publish that happens before the call and the least of the keys that the slots hold at the end of the call, and the values returned to one thread never increase (and the converse if the keys never decrease).
Indeed, (i) is the coherence of the atomic objects of C++ (the write-read, read-read and write-write coherence on one object), which holds for relaxed accesses, and the publishes of one slot, made by one thread, follow its program order; a publish that skips its store finds the key already there, so that the slot holds the same value as if it had stored it. (ii) is the code, which reads each slot once, at different times, so that no instant need exist at which the board held the value returned. For (iii), with the keys of a slot never increasing, a value read is at most the last one published before the call and at least the value of the slot at the end of the call; the minimum over the slots keeps both bounds, and two calls of one thread read each slot in the order of its publishes. Since the accesses are relaxed, a thread that reads \( k \) in a slot learns nothing of the writes that the owner made before publishing \( k \): a consumer that needs them (e.g., the node whose key is \( k \)) synchronizes otherwise, and uses the board only as a bound, which is the use of a search that prunes by the least \( f \) of its workers. A publish costs a load of a line that the owner keeps, and a store only when the key changes, which leaves the line shared in the caches of the readers otherwise; min() costs \( p \) loads, of lines that only their owners write.