From the free course Systems Programming in C and Unix Environments on Lykke

Concurrency and Multithreading

Key concepts: POSIX Threads (pthreads) · Shared Mutable Memory · Race Conditions and Data Races · Mutexes and Locks · Atomic Operations

Managing multiple execution threads within a single process and ensuring thread safety.

Concurrency and Multithreading

In the evolution of computing, we have transitioned from the era of increasing clock speeds to the era of increasing core counts. To leverage modern hardware, a programmer can no longer rely on a single sequential flow of execution. We must embrace Concurrency—the composition of independently executing processes—and Parallelism—the simultaneous execution of multiple computations.

In a systems context, specifically within the POSIX (Portable Operating System Interface) environment, this is achieved through Multithreading. While processes provide a heavy-weight abstraction with isolated memory, threads offer a light-weight alternative where multiple execution contexts exist within a single address space. This shared-memory model is the source of both the immense performance of multithreaded applications and the notorious complexity of debugging them.

The Shared Memory Model

What it is

In a multithreaded program, a single process contains multiple threads of execution. While each thread possesses its own Program Counter (PC), stack, and register set, they all reside within the same virtual address space. This means they share the same heap, global variables, and open file descriptors.

Why it matters

The primary motivation for shared memory is communication efficiency. In the multiprocess model (using fork()), communicating between a parent and child requires Inter-Process Communication (IPC) mechanisms like pipes, sockets, or shared memory segments managed by the OS. These involve system calls and context switches that are computationally expensive. Threads, by contrast, communicate simply by reading from and writing to the same memory addresses.

How it works

When a process starts, it begins with a single "main" thread. When additional threads are spawned, the OS allocates a new stack for each thread within the process's address space.

Feature Process (fork) Thread (pthread_create)
Memory Isolated (Copy-on-Write) Shared Address Space
Communication Explicit (IPC, Signals) Implicit (Shared Variables)
Creation Cost High (OS overhead) Low (Lightweight)
Context Switch Expensive (TLB flush) Cheaper (Same Page Tables)
Failure Impact One process crash is isolated One thread crash kills the process

The Shared Memory Axiom: Any object with a static or heap lifetime is accessible by all threads in the process. Only stack-allocated objects are "private" to a thread, and even then, they can be accessed by other threads if a pointer to the stack is shared (though this is highly dangerous).

POSIX Threads (pthreads)

What it is

pthreads is the standard execution model defined by POSIX.1c. It provides a C-language API for creating and managing threads. On Linux, this is typically implemented by the NPTL (Native POSIX Thread Library).

How it works: The Lifecycle

The lifecycle of a thread involves creation, execution, and termination. Unlike processes where the parent must wait(), threads can either be joinable or detached.

  1. Creation: pthread_create spawns a new thread. It requires a function pointer (the "start routine") and a single void * argument.
  2. Execution: The thread runs concurrently with the caller.
  3. Joining: pthread_join blocks the calling thread until the target thread terminates. This is essential for retrieving the thread's return value and cleaning up resources.
  4. Detaching: pthread_detach tells the system that the thread's resources can be reclaimed immediately upon termination, without a join.

Concrete Example: Vector Addition

Consider a program that sums two large arrays. We can split the work between two threads.

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

typedef struct {
    int *a;
    int *b;
    int *res;
    int start;
    int end;
} thread_data_t;

void* vector_add(void* arg) {
    thread_data_t *data = (thread_data_t *)arg;
    for (int i = data->start; i < data->end; i++) {
        data->res[i] = data->a[i] + data->b[i];
    }
    return NULL;
}

int main() {
    int N = 1000000;
    int *a = malloc(N * sizeof(int));
    int *b = malloc(N * sizeof(int));
    int *res = malloc(N * sizeof(int));

    pthread_t thread1, thread2;
    thread_data_t d1 = {a, b, res, 0, N/2};
    thread_data_t d2 = {a, b, res, N/2, N};

    pthread_create(&thread1, NULL, vector_add, &d1);
    pthread_create(&thread2, NULL, vector_add, &d2);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    printf("Addition complete.\n");
    return 0;
}

Common Pitfalls

  • Passing Stack Variables: Passing a pointer to a local variable in pthread_create that goes out of scope before the thread reads it.
  • Ignoring Return Values: pthread_create returns an integer error code, not errno. Always check it.
  • Memory Leaks: Joinable threads that are never joined or detached remain in the system as "zombie threads," leaking their stack memory.

Race Conditions and Data Races

What it is

A Race Condition is a flaw in a program where the output is dependent on the sequence or timing of uncontrollable events (such as the OS scheduler). A Data Race is a specific type of race condition where two or more threads access the same memory location concurrently, at least one access is a write, and no synchronization is used.

The Mechanics of the "Lost Update"

At the hardware level, an operation like counter++ is not atomic. It consists of three distinct steps:

  1. Load: Move the value from RAM to a CPU register.
  2. Increment: Add 1 to the register value.
  3. Store: Move the value from the register back to RAM.

If Thread A and Thread B both execute counter++ simultaneously, the following interleaving might occur:

Time Thread A Thread B Memory (counter)
T1 Load (val=10) 10
T2 Load (val=10) 10
T3 Increment (11) 10
T4 Store (11) 11
T5 Increment (11) 11
T6 Store (11) 11

Despite two increments, the value is 11, not 12. This is a lost update.

Mathematical Notation

Let $R_i(x)$ be a read of variable $x$ by thread $i$, and $W_i(x, v)$ be a write of value $v$ to $x$ by thread $i$. A data race exists if: $$\exists i, j : i \neq j \land (Access_i(x) \cap Access_j(x) \neq \emptyset) \land (Write_i(x) \lor Write_j(x))$$ where the accesses are not ordered by a "happens-before" relationship.


Mutexes and Locks

What it is

A Mutex (short for Mutual Exclusion) is a synchronization primitive used to protect Critical Sections—portions of code that access shared mutable resources.

How it works

A mutex acts like a "lock."

  1. A thread attempts to Lock the mutex.
  2. If the mutex is available, the thread gains ownership and proceeds.
  3. If the mutex is already held by another thread, the attempting thread blocks (sleeps) until the owner releases it.
  4. The owner calls Unlock, which wakes up one of the blocked threads.

Implementation in pthreads

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void increment_safe() {
    pthread_mutex_lock(&lock);
    // --- START CRITICAL SECTION ---
    counter++; 
    // --- END CRITICAL SECTION ---
    pthread_mutex_unlock(&lock);
}

Mutex Types and Behaviors

Mutex Type Description
Normal (Default) Standard lock. Deadlocks if a thread tries to lock it twice.
Recursive Allows the same thread to lock it multiple times; must unlock an equal number of times.
Error-Check Returns an error if a thread tries to relock or unlock a mutex it doesn't own.
Adaptive Spins in a tight loop for a short time before sleeping (performance optimization).

Pitfalls: Deadlocks

A Deadlock occurs when two or more threads are waiting for each other to release locks, creating a circular dependency.

The Coffman Conditions for Deadlock:

  1. Mutual Exclusion: Resources cannot be shared.
  2. Hold and Wait: Threads hold a resource while waiting for another.
  3. No Preemption: Resources cannot be forcibly taken.
  4. Circular Wait: A chain of threads exists such that $T_1$ waits for $T_2$, $T_2$ for $T_3 \dots$ and $T_n$ for $T_1$.

Prevention Strategy: Always acquire multiple locks in a globally defined, consistent order (e.g., always lock mutex_A before mutex_B).


Atomic Operations

What it is

Atomic operations are low-level instructions that are guaranteed to execute as a single, indivisible unit. They are performed by the hardware (CPU) without the need for OS-level locks.

Why it matters

Mutexes are "heavy." Locking a mutex involves a system call and potentially putting a thread to sleep, which takes thousands of CPU cycles. Atomics allow for "lock-free" programming, providing high-performance synchronization for simple data types.

How it works: Compare-and-Swap (CAS)

The heart of most atomic logic is the Compare-and-Swap operation. It takes three arguments: a memory location ($V$), an expected old value ($A$), and a new value ($B$). The CPU atomically performs:

  1. Read value at $V$.
  2. If $Value == A$, set $V = B$ and return true.
  3. Else, do nothing and return false.

C11 Atomics (stdatomic.h)

Modern C provides a standard way to use these instructions.

#include <stdatomic.h>

atomic_int counter = 0;

void increment_atomic() {
    // This is a single, atomic CPU instruction
    atomic_fetch_add(&counter, 1);
}

Comparison: Mutex vs. Atomic

Feature Mutex Atomic
Granularity Can protect large blocks of code Only protects single variables
Performance High overhead (context switches) Extremely low overhead
Blocking Yes (Pessimistic) No (Optimistic)
Complexity Easier to reason about Very difficult for complex logic

Variations and Advanced Synchronization

1. Condition Variables

While mutexes provide exclusion, Condition Variables provide signaling. They allow a thread to sleep until a specific condition becomes true (e.g., "the queue is no longer empty"). They are always used in conjunction with a mutex.

2. Read-Write Locks (pthread_rwlock_t)

In many systems, reads are frequent and writes are rare. A Read-Write lock allows multiple threads to read simultaneously, but requires exclusive access for writing. This significantly increases throughput in read-heavy workloads.

3. Semaphores

A semaphore is a counter-based synchronization primitive. A Binary Semaphore acts like a mutex, while a Counting Semaphore can allow a fixed number of threads (e.g., $N$) to access a resource pool.


Summary Table: Synchronization Primitives

Primitive Best Used For... Key Advantage Key Disadvantage
Mutex Protecting shared data structures Simple, prevents races Can cause deadlocks/latency
Atomic Simple counters/flags Maximum performance Limited to simple types
RW-Lock Databases / Cache lookups High read concurrency Write starvation possible
Cond Var Producer-Consumer patterns Efficient waiting Prone to "Lost Wakeup" bugs
Semaphore Throttling / Resource pools Limits total access Harder to debug than mutexes

Core Definitions for Review

  • Thread: The smallest unit of programmed instructions that can be managed independently by a scheduler.
  • Critical Section: A code segment where shared memory is accessed and must be protected from concurrent access.
  • Race Condition: A software bug where the output depends on the non-deterministic interleaving of threads.
  • Mutual Exclusion: The property that no two threads can be in a critical section for the same resource at the same time.
  • Liveness: A property of a system where "something good eventually happens" (e.g., no deadlocks).
  • Safety: A property of a system where "nothing bad ever happens" (e.g., no data races).

Recommended Practice

  1. Implement a thread-safe Queue using pthread_mutex_t and pthread_cond_t.
  2. Write a program that demonstrates a deadlock and then resolve it using lock ordering.
  3. Compare the performance of a global counter protected by a mutex versus one using atomic_fetch_add across 10 threads.
Concurrency and Multithreading - Systems Programming in C and Unix Environments - image 1
Concurrency and Multithreading - Systems Programming in C and Unix Environments - image 1
Concurrency and Multithreading - Systems Programming in C and Unix Environments - diagram 1
Concurrency and Multithreading - Systems Programming in C and Unix Environments - diagram 1
Concurrency and Multithreading - Systems Programming in C and Unix Environments - diagram 2
Concurrency and Multithreading - Systems Programming in C and Unix Environments - diagram 2

Source Materials

Study Systems Programming in C and Unix Environments on Lykke

This course page is free to open: signed out, you can read its first two sections, and signing in, on any plan, opens the rest. The free Lykke Chrome extension syncs your own Canvas courses, so ChatGPT, Claude and Muse can answer from your classes and deadlines. It only reads Canvas.

Add the free extensionSign in to open every section

All sections of Systems Programming in C and Unix Environments · Browse more course pages