Facebook Pixel

Exercise: Compare-and-Swap

This exercise puts the compare-and-swap (CAS) lesson into code.

Scenario

Model an atomic integer cell that starts at zero. The cell exposes one mutating primitive, compareAndSet, and two derived operations, set and inc, that must be implemented as CAS retry loops rather than direct assignments. Commands arrive one at a time in a single thread — this is a deterministic simulation of the CAS pattern, not actual concurrent execution.

Commands

CommandBehaviorOutput
["get"]Return the current valueThe current value as a string
["set", v]Unconditionally store v via a CAS loop"set <v>"
["cas", expected, new]Attempt a single CAS: write new only if current value equals expectedOn success: "ok <new>"; on failure: "fail <current>"
["inc"]Increment the value through a CAS retry loopThe new value as a string

All arguments are integers.

Example
Input
6
get
set 5
get
cas 5 10
cas 3 99
inc
Output
0
set 5
5
ok 10
fail 10
11
Explanation
The cell starts at 0, so `get` returns `0`. `set 5` stores 5 via a CAS loop and outputs `set 5`. `get` now returns `5`. The first `cas 5 10` succeeds because the current value equals the expected value of 5, so the cell becomes 10 and outputs `ok 10`. The second `cas 3 99` fails because the current value is 10, not 3; it outputs `fail 10` and leaves the cell unchanged. Finally, `inc` reads 10, computes 11, and the CAS succeeds, so the cell becomes 11 and outputs `11`.

Your task

Implement the skeleton in the editor below so the commands produce the output described above.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro