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

Mutex Pattern

Simple mutual exclusion with lock/unlock

Demonstrates: mutex pattern, critical section, deadlock-free locking

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
# Example 0059: Mutex Pattern
# Simple mutual exclusion with lock/unlock
# Demonstrates: mutex pattern, critical section, deadlock-free locking

MAX_OPERATIONS = 3

action Init:
    lock_holder = None
    counter = 0
    operations = 0

atomic action AcquireLock:
    require operations < MAX_OPERATIONS
    # Only acquire if not held
    require lock_holder == None

    lock_holder = "thread_a"

atomic action CriticalSection:
    require lock_holder == "thread_a"

    # Protected operation
    counter = counter + 1
    operations = operations + 1

atomic action ReleaseLock:
    require lock_holder == "thread_a"

    lock_holder = None

# Safety: counter only increments when lock is held
always assertion MutualExclusion:
    return lock_holder == None or lock_holder == "thread_a"

atomic action NoOp:
    if operations >= MAX_OPERATIONS:
        pass

Expected result (from fizz):

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

Source on GitHub

Language features used

Assertions, Flow Modifiers