Skip to main content

Lesson 13 of 26 · 11 min read

Threads, shared memory, and race conditions

Understand how threads share one address space with private stacks, trace exact assembly interleavings that cause data races, and learn the POSIX Thread API.

Four concurrency basics: Shared heap, Thread stacks, R-M-W race, and Atomicity lock.
Threads share one address space with private stacks; unprotected read-modify-write steps race across timer interrupts.
Course syllabus · lesson 13 of 26
In this lesson

A thread gives a process another place to execute. A server can handle one connection while another waits for a reply. A computation can assign different rows of an array to different cores. In both cases threads share memory, so one thread can publish a result simply by writing an object that another can reach. The same sharing makes an ordinary increment surprisingly hard to reason about.

Two-column thread interleaving showing Thread 1 loading counter=0 and adding 1, getting interrupted before storing, Thread 2 reading stale 0 and writing 1, and Thread 1 overwriting with 1 instead of 2.
Open full-size diagram
In this machine-code example, both workers load zero before either stores. Both write one, so one increment is lost.

Replay a lost counter update

Thread A read 0, Thread B —, Shared counter 0Thread Aread 0Thread B—Shared counter0

Step 1 of 4

A reads zero

Thread A loads the shared counter into a register. The counter still holds 0.

One address space, several execution contexts

A process provides an address space and resources such as a file descriptor table. Its threads execute the same program and can address the same globals, heap allocations, and mapped files. Two threads using the same descriptor can also affect the same underlying open file state. For example, ordinary reads on a shared open file description can advance its file offset. The OS schedules each runnable thread as an execution context with its own program counter, stack pointer, general registers, and scheduling state.

On a switch from thread A to thread B in the same process, the kernel saves A's execution state and restores B's. The register-save area and associated scheduling records are often described together as the thread control block. Both threads normally use the same address-space mappings, so switching between them can retain the process's page-table context. On multiple cores the two register sets can be live at once. On one core the same hardware registers hold different values over time, with the kernel accounting for the suspended thread's values.

Each thread needs its own stack because its call chain and local variables can have different lifetimes. If A is three functions deep when B starts a call, B needs a separate place to save its return addresses. Those stacks are still mapped inside the shared address space. A pointer to a stack object can be passed to another thread if the object remains alive and accesses are properly synchronized. The owning thread returning from the function can end the object's lifetime even while some other thread still holds its address. Thread-local storage offers separate instances of a variable, while ordinary globals have one shared instance.

The three steps inside an increment

Consider an illustrative x86 machine-code sequence for a shared memory location named counter. Begin with zero in memory. Each worker executes these instructions once.

Code exampleAssembly
movl counter(%rip), %eax
addl $1, %eax
movl %eax, counter(%rip)

The first instruction copies the shared value into the executing thread's register. The second changes only that register. The third publishes the register value back to the shared address. Each thread follows its own instruction order. The order between threads is open. A timer interrupt can suspend A after the add, while another core can run B even without a timer interrupt. For the trace, assume the loads and stores appear in a single interleaving and that both threads access the same aligned word.

If A and B load before either stores, both compute one in private registers. Two stores follow, both writing one. A store can replace an update with precisely the same value, so examining the final memory contents cannot tell you how many stores ran. If A's store precedes B's load, B sees one and computes two. Sorting whole source statements into a timeline hides the intermediate state that distinguishes the outcomes.

There are two kinds of guarantee to keep separate when moving from this machine example to C. An aligned machine load can be indivisible, yet a load followed by arithmetic and a store contains several independently visible operations. At the language level, unsynchronized overlapping accesses to a plain C object, with at least one write and no ordering between them, form a data race. The behavior is undefined. The possible results we enumerate belong to the stated machine model. An optimizer can keep a plain variable in a register or transform a loop in ways the trace does not capture. Declaring the variable volatile does not provide a C synchronization operation.

A race condition is a broader correctness issue in which the outcome depends on timing. For example, individually atomic loads and stores can still lose an increment. Each access is well defined, but the sequence has no indivisible update. This distinction explains why replacing a plain load and store with atomic loads and stores does not by itself make the compound operation correct.

Design around an invariant

For this counter, the intended invariant at operation boundaries is simple. Starting at zero, the counter equals the number of increments that have taken effect. The critical section is the code that must execute with exclusive access to preserve that invariant. Placing only the final store inside a mutex leaves room for both workers to calculate the result from the same older value. Protect the load, arithmetic, and store with one acquisition of a mutex shared by all users of the counter.

Holding the mutex does not prevent preemption. If A is suspended inside the section, B has to wait for A to unlock. A correct mutex also provides memory ordering. Writes performed by A before unlocking become visible to B through a later successful acquisition of that same mutex. Code elsewhere that reads the counter while updates are in progress must use the same mutex or follow another synchronization protocol that makes the read safe.

The protected region can span several fields. Imagine moving one item from a pending list to a completed list and incrementing a completed count. If readers need the count to match the list length, maintain both under one synchronization policy. Updating the count atomically would still let a reader observe it before the list is updated. First name the invariant a reader expects. Then decide which operations must appear to take effect together.

A single independent total can instead use a C atomic read-modify-write, such as atomic_fetch_add_explicit(&counter, 1, memory_order_relaxed) on an atomic counter. Its load and update are indivisible relative to other atomic operations on the same object. Two increments starting at zero take effect in some order and return distinct old values, zero and one. Relaxed ordering is enough for the arithmetic on this object. A thread that uses a flag to publish the contents of a separate object requires ordering for that publication as well. A mutex gives a convenient starting point when a protected invariant includes multiple locations.

Starting workers and joining them

pthread_create starts a routine with a void * argument and writes a thread identifier through its first parameter. The new routine can begin before the creator returns from pthread_create, or the creator can continue first. A null attributes argument selects the defaults, including a joinable thread. Initialize each argument before creation, keep it alive until the worker has finished using it, and give concurrent workers distinct argument objects when their inputs differ.

pthread_join waits for a particular joinable worker to terminate and can retrieve its void * result. It also provides the synchronization needed for the caller to observe writes performed by that worker before termination. Returning the address of a local variable in the worker would leave the caller with a pointer to an object whose lifetime has ended. A worker may instead write to storage provided by its caller, which can read it after joining. This example also uses joins to keep the argument array in scope.

Lifetime and synchronization are separate checks for an argument. Suppose a loop passes the address of its loop index to every worker. Even if the index stays in scope until all the joins, the creator can change it before any worker reads it. Concurrent reads and writes can then race on the index itself. A distinct array element for each worker fixes the problem when the creator initializes the elements before launch and leaves them alone until the workers finish. This is also why copying the argument pointer into a local variable in the worker would be insufficient. That creates another pointer to the same shared object. The array below gives each worker a different object to read and uses the mutex only for the location the workers actually modify together.

Code exampleC
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static int counter;

static void *worker(void *arg)
{
    const int amount = *(const int *)arg;
    if (pthread_mutex_lock(&mutex) != 0)
        abort();

    counter += amount;

    if (pthread_mutex_unlock(&mutex) != 0)
        abort();
    return NULL;
}

int main(void)
{
    int amounts[] = {1, 1};
    pthread_t threads[2];

    for (int i = 0; i < 2; ++i) {
        if (pthread_create(&threads[i], NULL, worker, &amounts[i]) != 0)
            abort();
    }
    for (int i = 0; i < 2; ++i) {
        if (pthread_join(threads[i], NULL) != 0)
            abort();
    }

    printf("%d\n", counter);
    return 0;
}

Compile with cc main.c -pthread. Joining in creation order says nothing about which worker acquires the mutex first. The joins establish that both updates are complete before the main thread prints. If the workers omitted the mutex, joining both would still leave their accesses unordered relative to each other. If the workers wrote to two distinct result slots, shared addition could instead be delayed until the main thread has both results. This is often the simplest way to avoid synchronization on an update path.

Worked trace

Return to the unprotected assembly model. Write the value held by each thread's register alongside the shared word. A dash means the thread has yet to load. Resuming A after B has finished restores A's saved register value, even though the memory word has changed.

Code exampleTrace
Step   Operation                  A eax   B eax   counter
0      Initial state              -       -       0
1      A loads counter            0       -       0
2      A adds one                 1       -       0
3      B loads counter            1       0       0
4      B adds one                 1       1       0
5      B stores its value         1       1       1
6      A stores its value         1       1       1

List the possibilities by looking at the second load. If it happens before the first store, both loads see the initial value. If it happens after the first store, the first increment is complete and the second builds on it. For two identical updates this gives just one or two as the final value under the model. With the mutex in place, the interleaving in the table becomes impossible because A owns the mutex from step one through its store. B's load must then occur after A's store and unlock, or B must complete the whole sequence before A.

This style of reasoning also checks patches. Try moving the lock acquisition down one instruction at a time. As soon as the load can execute before acquisition, A and B can save the same original value again. Try moving the unlock up before the store. B can acquire the mutex after A releases it and still load the old memory word. These schedules identify the first and last operation the lock must cover.

Change one input

Keep the three-instruction model and start with ten. Change the amounts to five for A and three for B. Trace the schedule where both loads precede both stores. The registers contain fifteen and thirteen. If A stores last, the result is fifteen and B's increment is lost. If B stores last, the result is thirteen and A's increment is lost. If one store precedes the other load, the second load sees the first update and the result is eighteen in either serial order.

Revisit the protected program with these amounts and initialize counter to ten. The answer remains eighteen even if the creation order is reversed or a worker is paused immediately before the store. A changed scheduler can change who waits. It cannot admit the second worker to the protected region while the first owns the mutex. Lesson 14 follows that guarantee down to atomic instructions and kernel wait queues.

Before you move on

Try it in your workspace

Draw two execution columns for two threads incrementing a shared counter starting at 0. Show the exact mov/add/mov interleaving that loses an update and leaves counter = 1 instead of 2.

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.