Skip to main content

Lesson 17 of 26 · 11 min read

Concurrency bugs, deadlock, and event-based servers

Diagnose atomicity and ordering bugs, prevent deadlocks by breaking Coffman's four conditions, and compare threads against single-threaded async event loops.

Four concurrency failure and control concepts: Atomicity bug, Coffman cycle, Total lock order, and Event select().
Diagnose atomicity and ordering bugs, prevent deadlocks via lock ordering, and compare threads with event loops.
Course syllabus · lesson 17 of 26
In this lesson

A server can stop serving requests because two threads each hold the lock the other needs. It can also fail while every thread is still running, for example by using a pointer before initialization or after another thread has changed it. These failures demand different questions. Which operations must occur together? Which must occur first? What can still run while a thread or request is waiting?

Circular deadlock between Thread 1 holding L1 waiting for L2 and Thread 2 holding L2 waiting for L1, Coffman's four necessary deadlock conditions, breaking circular wait by lock ordering, and non-blocking select() event-loop comparison.
Open full-size diagram
Acquiring locks in a consistent order prevents a circular wait among those locks. The event loop illustrates a different way to schedule concurrent work.

Find and break a deadlock cycle

Thread A holds 1, Thread B holds 2, Lock 1 owned by A, Lock 2 owned by BThread Aholds 1Thread Bholds 2Lock 1owned by ALock 2owned by B

Step 1 of 3

Acquire opposite locks

A holds Lock 1 while B holds Lock 2. The arrows show which thread owns each lock.

Atomicity and ordering violations

An atomicity violation splits what the application assumes is one operation. Suppose a thread locks a mutex to check that a shared diagnostic pointer is nonnull, unlocks, then locks again to dereference the pointer. Another thread can acquire the same mutex between those two sections, clear the pointer, and free its target. Each individual read of the pointer can be synchronized, yet the earlier check no longer establishes that the later dereference is safe. Keep the check and use inside one critical section, or obtain a reference under the lock that keeps the target alive for use after release.

An ordering violation occurs when one operation needs another to run first. Suppose a parent stores a worker descriptor after starting a thread, and the worker needs that descriptor on entry. A mutex around both accesses ensures mutual exclusion, but the worker can acquire it first and observe an uninitialized descriptor. Where possible, initialize the data before creating the thread. When initialization must be deferred, publish it under a mutex and use a separate readiness predicate. The worker waits in a loop until the predicate holds. If the descriptor becomes ready before the worker waits, the predicate still records the change.

Write down the execution order the application assumed, then look for the first place another thread can invalidate it. Atomicity violations call for an uninterrupted logical operation or a lifetime guarantee. Ordering violations call for a way to communicate when the prerequisite has happened. Both can appear intermittently under the same workload.

Deadlock and Coffman's four conditions

For exclusive resources such as ordinary mutexes, draw a wait-for edge from each blocked thread to the thread that owns the resource it needs. If A waits for a mutex owned by B, and B waits for one owned by A, the edges form a cycle. Each thread in the cycle needs another member to run past an acquisition before it can release its resource. Threads outside the cycle may still work.

Four conditions are necessary for resource deadlock in Coffman's model.

  1. Mutual exclusion. Some resource is available to at most one holder at a time. For a single shared counter, an atomic read-modify-write can eliminate the need to hold a separate lock. Multi-object invariants require a protocol that covers all participating fields.
  2. Hold and wait. A thread retains one resource while requesting another. An all-or-nothing reservation protocol can either grant the whole set or let the caller wait with none. A coarse outer acquisition lock can serialize groups of lock acquisitions if all participants use it and know the full set in advance.
  3. No preemption. A held resource is released only through the owner's protocol. A failed pthread_mutex_trylock can make a caller voluntarily give up its first lock and retry, interrupting a would-be cycle. Any partial mutation must be undone or postponed before release. Repeatedly colliding and retrying can cause livelock, where threads run but complete nothing.
  4. Circular wait. Threads wait for resources held by the next thread in a closed chain. A global lock rank prevents this when every thread acquires additional locks in strictly increasing rank order.

For rank ordering, suppose a cycle existed. Follow it from a thread's held lock to the lock it is waiting for. The requested lock has a higher rank. Following the whole cycle would produce a sequence of strict increases that ends at its starting rank, which is impossible. In an application with dynamic objects, unique immutable IDs can supply a total order. In C, relational comparison of pointers to unrelated objects is not a portable ordering rule. The rank must also cover acquisitions hidden in helpers or callbacks. A single call path that acquires in reverse can reintroduce a cycle.

Deadlock differs from starvation, where other requests finish while one caller is repeatedly bypassed, and from livelock, where callers keep changing state without completing their requests. A lock order removes the cycles governed by that order. A slow holder, unfair scheduling, or a dependency involving a condition wait can still stop specific work from completing. Debugging starts by identifying actual holders and waiters before deciding which progress failure is present.

Event loops schedule work through readiness

An event loop holds application state in data structures and chooses handlers when events arrive. A single loop thread runs each synchronous handler to completion before dispatching the next one. State accessed only by that loop can often be updated without a mutex, since another handler cannot execute concurrently with the current one. Once a handler yields by returning, later handlers may run in any permitted order. They can still violate an application-level ordering assumption across those turns.

select() and poll() report readiness for operations on descriptors, such as reading a socket with data available. With select(), build a watch set and pass a fresh copy each iteration, because the system call overwrites the supplied sets with the ready subset. Pass one more than the largest watched descriptor as its first argument. With poll(), each entry has requested events and a return field for observed events. Handle errors, interruptions, and hangups along with readability and writability.

Readiness is permission to try an operation. With nonblocking sockets, a read can still return EAGAIN, and a write can send only part of the buffer. Keep the unsent suffix and register interest in writability while bytes remain. A handler can also set a work budget and return after processing a bounded batch. Otherwise one hot socket can delay every other request even though all its individual operations are nonblocking.

Waiting inside the event demultiplexer is appropriate when there is no useful handler to run. Waiting inside a handler for one client's blocking file read is different. Every other ready client must wait for that call too. select() reporting a regular file ready does not guarantee that reading its data will avoid a storage wait. Even a page fault can delay a loop that avoids blocking calls explicitly.

Asynchronous I/O and continuations

Asynchronous I/O separates submission from completion. A readiness notification tells the application an operation can be attempted. An AIO completion reports the outcome of an operation previously submitted. With the POSIX AIO model described in OSTEP, aio_read() accepts a request structure describing the file descriptor, buffer, byte count, and offset. Successful submission leaves work outstanding. The application can use aio_error() to check whether it is still in progress and use aio_return() once after completion to retrieve the result. Completion can also be delivered through the notification mechanism configured for the request. Keep its control block and buffer alive until the operation has finished.

With blocking code, a thread's stack remembers where to send bytes when read() returns. In an event loop the submission handler has returned by then. Store that missing continuation explicitly, for example in a request object containing a unique request ID, destination connection, buffer, and current offset. A completion handler looks up the request, checks how many bytes arrived, handles errors or early end of file, then queues those bytes for the correct connection. Using a request ID also distinguishes concurrent operations against the same descriptor. A connection can close while the read is pending, so the object should retain enough identity to avoid sending data to an unrelated connection that later reuses the descriptor number.

Some designs perform blocking file operations on a worker pool and deliver the results as events. This retains a responsive network loop at the cost of worker scheduling and synchronization at the handoff. Likewise, multiple loops can exploit several cores when each owns a set of connections. Shared mutable data then needs explicit sharing rules again. In either design, limiting outstanding work bounds the memory used by pending requests and their buffers.

Consider two clients, X and Y. A handler for X submits a disk read and returns. While it is pending, a handler for Y submits a smaller read. Suppose Y completes first and the event loop sees Y's completion before X's. The loop can queue Y's response immediately because each request object records its own destination and byte count. If both reads belong to one connection with ordered responses, completion order is separate from response order. The loop can keep per-connection sequence numbers and hold the second response until it can send the first. With a limit of eight reads and a 64 KiB buffer per read, the buffers for the outstanding reads occupy at most 512 KiB. Completed responses waiting to be sent need a bound of their own, since a slow peer can let that queue grow after the read slots have been released.

Worked trace

Accounts A and B begin with balances of 100 and each has a nonrecursive mutex. T1 wants to transfer 50 from A to B. T2 wants to transfer 25 from B to A.

Code exampleTrace
Step   T1                              T2
1      Acquires A                      About to run
2      Holds A                         Acquires B
3      Holds A                         Waits for A
4      Waits for B                     Waits for A

At step four the edges are T1 to T2 and T2 to T1. Each thread holds one lock, waits for a mutually exclusive second lock, and cannot force the owner to release it. Assign A rank one and B rank two. Both transfers now lock A first. If T1 wins, it takes B, updates the balances to 50 and 150, and releases both locks. T2 then takes both and updates the balances to 75 and 125. The direction of money and the direction of lock acquisition are independent.

In a single event loop, a transfer that updates both balances in one synchronous handler can likewise finish before another transfer starts. If the handler submits an asynchronous check and returns between reading and changing those balances, another handler may change the state first. When the check completes, the continuation must validate against the current balances or use a reservation recorded before it yielded.

Change one input

Keep ranked locking and change the destination of T1's transfer from B to A. A routine that tries to lock two arguments blindly will attempt to acquire its own nonrecursive mutex again. With a normal mutex, that can create a wait-for edge from T1 to itself. Detect account identity before acquiring a lock pair. If the API treats a self-transfer as a no-op, it can return without taking two locks. If it still needs to validate the account and amount, it can do so under one lock. The next lesson follows async work down to device requests, interrupts, and DMA.

Before you move on

Try it in your workspace

Draw the circular wait cycle when Thread 1 acquires Lock A -> Lock B while Thread 2 acquires Lock B -> Lock A. Apply total lock-address ordering to break it, then contrast threads with a non-blocking select() event loop.

Keep a short note of what you tried, what passed, and what you still need to check.

Your practice record

0 of 3 checked.

Saved in this browser when storage is available. Uncheck any item to revisit it. This is your own record, not an assessment.