FizzBee
GitHub Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Compare-And-Swap Pattern

Atomic compare-and-swap for lock-free algorithms

Demonstrates: CAS operation, lock-free updates, ABA problem awareness

Run in playground
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Example 0077: Compare-And-Swap Pattern
# Atomic compare-and-swap for lock-free algorithms
# Demonstrates: CAS operation, lock-free updates, ABA problem awareness

action Init:
    shared_value = 0
    operations = 0

atomic action CASIncrement:
    require operations < 3

    # Read current value
    expected = shared_value
    new_value = expected + 1

    # CAS: update only if value unchanged
    if shared_value == expected:
        shared_value = new_value
        operations = operations + 1

atomic action CASDecrement:
    require operations < 3
    require shared_value != 0

    # Read current value
    expected = shared_value
    new_value = expected - 1

    # CAS: update only if value unchanged
    if shared_value == expected:
        shared_value = new_value
        operations = operations + 1

atomic action CASSet:
    require operations < 3

    # Direct set to specific value
    expected = shared_value
    target = 10

    if shared_value == expected:
        shared_value = target
        operations = operations + 1

# Safety: value changes atomically
always assertion ValidValue:
    return shared_value >= 0

# Safety: operations bounded
always assertion OperationsBounded:
    return operations <= 3

atomic action NoOp:
    if operations >= 3:
        pass

Expected result (from fizz):

StateSpaceOptions: options:{max_actions:100 max_concurrent_actions:2}
Nodes: 15, queued: 0
Valid Nodes: 15 Unique states: 15
IsLive: true
PASSED: Model checker completed successfully

Source on GitHub

Language features used

Assertions, Flow Modifiers