# Read-Write Lock Pattern

> A read-write lock as a runnable model: many concurrent readers or one exclusive writer, checked so no reader ever overlaps a writer and at most one writer holds the lock.

Canonical: https://fizzbee.io/design/patterns/read-write-lock/
Source: https://github.com/fizzbee-io/fizzbee/tree/main/examples/references/13-01-02-read-write-lock


Multiple readers OR single writer

**Demonstrates:** readers-writer lock, concurrent reads, exclusive writes

```fizz
# Example 0064: Read-Write Lock Pattern
# Multiple readers OR single writer
# Demonstrates: readers-writer lock, concurrent reads, exclusive writes

MAX_OPS = 3

action Init:
    readers = 0
    writer = False
    data = 0
    operations = 0

atomic action AcquireReadLock:
    require operations < MAX_OPS
    # Can read if no writer
    require not writer

    readers = readers + 1

atomic action ReleaseReadLock:
    require readers > 0

    readers = readers - 1
    operations = operations + 1

atomic action AcquireWriteLock:
    require operations < MAX_OPS
    # Can write if no readers and no writer
    require readers == 0 and not writer

    writer = True

atomic action ReleaseWriteLock:
    require writer

    writer = False
    data = data + 1
    operations = operations + 1

# Safety: no concurrent readers and writer
always assertion NoReadersWithWriter:
    if writer:
        return readers == 0
    return True

# Safety: at most one writer
always assertion SingleWriter:
    return writer == True or writer == False  # Boolean check

atomic action NoOp:
    if operations >= MAX_OPS:
        pass
```
Run it in the FizzBee playground: https://fizzbee.io/play


**Expected result** (from `fizz`):

```
StateSpaceOptions: options:{max_actions:100 max_concurrent_actions:2}
Nodes: 7509, queued: 0
Skipping dotfile generation. Too many Nodes: 7509
Valid Nodes: 7509 Unique states: 7509
IsLive: true
PASSED: Model checker completed successfully
```

[Source on GitHub](https://github.com/fizzbee-io/fizzbee/tree/main/examples/references/13-01-02-read-write-lock)

## Language features used

[Assertions](/reference/language/assertions/), [Flow Modifiers](/reference/language/flow-modifiers/)

