Lesson 7 · Synchronization and deadlocks

Readers Writers Problem

Any number of readers may share the data, but a writer needs it alone. The first solution is short, correct — and starves writers indefinitely.

Readers Writers Problem concept diagramA visual explanation of the layout and operations shown in this lesson.readers share the resource; a writer needs it alonereadersR1R2R3all three read at oncewriterW1 — blockedreadcount = 3first reader locksthe resource for alllast reader releaseswrtheld — writer waitsshared databeing read by 3 readersthis version favours readers — a steady stream of them can starve the writer
1

Many Readers or One Writer

The readers-writers problem is a classic operating system exercise in process synchronization. Several processes share one data object: readers only examine it, while writers modify it. The problem is to allow as much concurrency as possible without ever letting a write overlap with any other access.

The rule follows from what each operation does. Two readers running together cannot interfere, because neither changes anything — so any number of readers may read at the same time. A writer changes the data, so it must have exclusive access: no other writer, and no readers either.

A naive mutex around every access would be correct but wasteful, because it would serialise readers that could safely run in parallel. The problem is therefore about writing a solution that keeps reads concurrent while still guaranteeing a writer runs alone.

  • Reader + reader: allowed together
  • Reader + writer, or writer + writer: never together
  • The classic solutions differ in who gets priority: readers, writers, or neither (fair)
2

The Semaphore Solution

  1. Reader: wait(mutex), readcount++, if readcount == 1 then wait(wrt), signal(mutex).
  2. Reader reads the data: concurrently with other readers.
  3. Reader: wait(mutex), readcount--, if readcount == 0 then signal(wrt), signal(mutex).
  4. Writer: wait(wrt), write, signal(wrt): no counter, no special case.

Solving the readers writers problem using semaphores takes two semaphores and one integer. The steps above are the whole of it.

wrt (initially 1) is the real lock on the data. A writer takes it for the whole write. mutex (initially 1) protects the counter, not the data. readcount counts readers currently inside.

The trick is that readers do not each lock the data. The first reader to arrive takes wrt on behalf of every reader, and the last reader to leave releases it. Readers in between simply walk in.

readcount must be protected because readcount++ is a read-modify-write on shared state — exactly the non-atomic sequence that creates a race condition.

  • The writer's code is three lines and has no counter
  • mutex is held only around the counter, never during the read
  • Only the first reader in and the last reader out touch wrt, so readers in between never block each other
3

Why This Version Starves Writers

The solution above solves the first readers writers problem: readers get priority. An arriving reader checks only readcount, so it walks in even while a writer is already queued. It is correct in the safety sense — no reader ever overlaps a writer — but it offers no liveness guarantee for writers.

Under a steady read load, readcount never returns to zero, so signal(wrt) is never executed and the writer waits forever. That is starvation, not deadlock: the writer could run, but its turn never comes. On a busy server this is the normal case, not a corner case.

The second readers writers problem flips the priority: once a writer is waiting, no new reader may enter. That starves readers instead. A fair variant puts both behind a single queueing semaphore so arrival order is preserved and neither side can starve.

  • First problem: readers priority, writers can starve
  • Second problem: writers priority, readers can starve
  • Fair variant: FIFO turnstile, no starvation either way
  • Real reader-writer locks each pick one of these policies
Implementation

Code in Python, C++ and Java

import threading

readcount = 0
mutex = threading.Lock()        # guards readcount, NOT the data
wrt = threading.Semaphore(1)    # the real lock on the data

data = {"value": 0}

# Only for the demo: each reader reports when it is inside, then stays
# until main lets them all go, so the run follows one fixed order.
leave = threading.Event()


def reader(name, inside):
    global readcount

    with mutex:
        readcount += 1
        if readcount == 1:
            wrt.acquire()  # first reader locks out writers for everyone
        print(f"{name} reading value={data['value']}  readers={readcount}")
    inside.set()
    leave.wait()

    with mutex:
        readcount -= 1
        if readcount == 0:
            wrt.release()  # last reader lets writers back in


def writer(name):
    wrt.acquire()  # exclusive: no reader, no other writer
    data["value"] += 1
    print(f"{name} wrote  value={data['value']}")
    wrt.release()


def start(target, *args):
    t = threading.Thread(target=target, args=args)
    t.start()
    return t


def main():
    threads = []
    for name in ["R1", "R2"]:
        inside = threading.Event()
        threads.append(start(reader, name, inside))
        inside.wait()

    threads.append(start(writer, "W1"))  # blocks: the readers hold wrt

    inside = threading.Event()
    threads.append(start(reader, "R3", inside))  # walks past the waiting writer
    inside.wait()

    leave.set()
    for t in threads:
        t.join()

    print(f"final value: {data['value']}")


if __name__ == "__main__":
    main()
#include <future>
#include <iostream>
#include <mutex>
#include <semaphore>
#include <string>
#include <thread>
#include <vector>
int readcount = 0;
std::mutex countMutex; // guards readcount, NOT the data
std::binary_semaphore wrt(1); // the real lock on the data; any thread may release it
int data = 0;
// Only for the demo: each reader reports when it is inside, then stays
// until main lets them all go, so the run follows one fixed order.
std::promise<void> leavePromise;
std::shared_future<void> leave = leavePromise.get_future().share();
void reader(const std::string& name, std::promise<void>* inside) {
    {
        std::lock_guard<std::mutex> lock(countMutex);
        readcount++;
        if (readcount == 1) wrt.acquire(); // first reader locks out writers
        std::cout << name << " reading value=" << data << "  readers=" << readcount << '\n';
    }
    inside->set_value();
    leave.wait();
    {
        std::lock_guard<std::mutex> lock(countMutex);
        readcount--;
        if (readcount == 0) wrt.release(); // last reader lets writers back in
    }
}
void writer(const std::string& name) {
    wrt.acquire(); // exclusive access
    data++;
    std::cout << name << " wrote  value=" << data << '\n';
    wrt.release();
}
int main() {
    std::vector<std::thread> threads;
    std::promise<void> inside[3];
    for (int i = 0; i < 2; i++) {
        threads.emplace_back(reader, "R" + std::to_string(i + 1), &inside[i]);
        inside[i].get_future().wait();
    }
    threads.emplace_back(writer, "W1"); // blocks: the readers hold wrt
    threads.emplace_back(reader, "R3", &inside[2]); // walks past the waiting writer
    inside[2].get_future().wait();
    leavePromise.set_value();
    for (auto& t : threads) t.join();
    std::cout << "final value: " << data << '\n';
}
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
class Main {
    static int readcount = 0;
    static final Object countMutex = new Object(); // guards readcount, NOT the data
    static final Semaphore wrt = new Semaphore(1); // the real lock on the data
    static int data = 0;
    // Only for the demo: each reader reports when it is inside, then stays
    // until main lets them all go, so the run follows one fixed order.
    static final CountDownLatch leave = new CountDownLatch(1);
    static void reader(String name, CountDownLatch inside) throws InterruptedException {
        synchronized (countMutex) {
            readcount++;
            if (readcount == 1) wrt.acquire(); // first reader locks out writers
            System.out.println(name + " reading value=" + data + "  readers=" + readcount);
        }
        inside.countDown();
        leave.await();
        synchronized (countMutex) {
            readcount--;
            if (readcount == 0) wrt.release(); // last reader lets writers back in
        }
    }
    static void writer(String name) throws InterruptedException {
        wrt.acquire(); // exclusive access
        data++;
        System.out.println(name + " wrote  value=" + data);
        wrt.release();
    }
    interface Body {
        void run() throws InterruptedException;
    }
    static Thread start(Body body) {
        Thread t = new Thread(() -> {
        try {
        body.run();
        } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        }
        });
        t.start();
        return t;
    }
    public static void main(String[] args) throws InterruptedException {
        List<Thread> threads = new ArrayList<>();
        for (String name : new String[] {"R1", "R2"}) {
            CountDownLatch inside = new CountDownLatch(1);
            threads.add(start(() -> reader(name, inside)));
            inside.await();
        }
        threads.add(start(() -> writer("W1"))); // blocks: the readers hold wrt
        CountDownLatch inside = new CountDownLatch(1);
        threads.add(start(() -> reader("R3", inside))); // walks past the waiting writer
        inside.await();
        leave.countDown();
        for (Thread t : threads) t.join();
        System.out.println("final value: " + data);
    }
}
Watch it run

Step through it

Running on R1, R2 arrive, then W1, then R3 - first readers-writers solution

readcount0readers insidewrt11 = data is freemutex1guards readcountwaitingoutsidecriticalsectionnobody waitingempty
Nobody is inside yet.
Step 1

the shared data and its two guards

readcount tracks how many readers are currently inside. wrt is the semaphore that gives exclusive access to the data — a writer holds it alone, and the FIRST reader holds it on behalf of all readers. The other semaphore, mutex, protects readcount itself.

Output
1 / 12
4

Where You Meet This in Real Code

Every major platform ships a reader–writer lock built on this idea: pthread_rwlock_t in POSIX, ReentrantReadWriteLock in Java, sync.RWMutex in Go, std::shared_mutex in C++17.

They differ exactly where the classical problem does — in policy. Java's lock has an optional fairness flag. Go's RWMutex blocks new readers once a writer is waiting, which is the writer-preferring variant chosen to bound writer latency.

The practical rule: a reader–writer lock only pays off when reads dominate and the critical section is long enough to matter. For a short read on a single word, an atomic load is cheaper than the bookkeeping.

  • pthread_rwlock_t — policy is implementation-defined
  • Go sync.RWMutex — writer-preferring by design
  • Java ReentrantReadWriteLock — fairness is a constructor flag