Skip to content
BytePatterns

Retries in a Compare-and-Swap Loop

EasyConcurrency#compare-and-swap#step-simulation~15m

Problem

Several threads add their own amount to one shared value without a lock. Each thread loops over two steps: read the shared value into a private snapshot, then compare-and-swap. The swap succeeds only if the shared value still equals the snapshot, in which case it writes snapshot + amount and the thread is done; otherwise the swap fails, nothing is written, and the thread starts over with a fresh read. You are given the starting value, each thread's amount, and the schedule as a list of thread numbers, where each entry lets that thread take its next step. Entries for a thread that has already finished are ignored. Return the final value and how many swaps each thread lost.

Examples

Input:  start = 0, amounts = [5, 7], schedule = [0, 1, 0, 1, 1, 1]
Output: (12, [0, 1])
Why:    thread 1's swap fails because thread 0 changed the value after thread 1 read it, so it rereads and tries again
Input:  start = 0, amounts = [1, 1, 1], schedule = [0, 1, 2, 0, 1, 2, 1, 2, 1, 2, 2, 2]
Output: (3, [0, 1, 2])
Why:    all three read 0, only one swap per round can win, and thread 2 loses twice
Input:  start = 10, amounts = [3], schedule = [0, 0]
Output: (13, [0])
Why:    edge case, with no other writer the first swap always succeeds

Hints

0 / 3

Stuck on the idea rather than the code? Compare-and-Swap covers it.