Parallel Programming

Reading map

Previous: Networks and Protocols Reading map Next: Inside the Kernel

Volume II: Systems Programming (Chapter 7)Code & tests Chapter diagrams Download editable SVGs

Parallel programming divides one task into parts that can make progress at the same time. That can reduce elapsed time when the parts perform substantial independent computation. It can also make a program slower, less predictable, and much harder to prove correct when the parts share mutable data.

The central problem is not creating threads. It is preserving the relationships, or invariants, that must remain true while independently scheduled computations observe and modify the same state.

Chapter Map

Detailed notes - 7: Parallel programs and shared data

1

parallel programming: divide work into subtasks that can execute concurrently

  • threads run functions alongside the main program
  • threads share the process's memory, including globals and dynamically built structures

2

multithreading = programming with multiple threads of execution

  • Russian terminology often translates this as "multistream" programming
  • thread / control flow refers to execution, not transferred data

3

thread, flow, and stream have overlapping Russian translations

  • an I/O stream carries data; a thread executes instructions
  • keep the two programming concepts distinct

4

book uses "thread" for one execution thread

  • uses the conventional Russian term for multithreaded programming

5

multicore processors made parallel programming widely available

  • speed may instead be limited by network, storage, memory, or bus throughput
  • dependent steps must still execute in sequence
  • identifying enough independent work is essential to useful parallelism
  • author's broad criticism of parallel programming is a viewpoint, not a universal rule

6

Amdahl's law: the serial part limits total speedup

  • alpha = fraction that remains sequential; p = processor count
  • ideal speedup S = 1 / (alpha + (1 - alpha) / p)
  • assumes perfect parallelization of the remaining fraction
  • alpha = 1/4: 10 processors -> about 3.08x; 21 -> 3.5x; 100 -> about 3.88x
  • even infinitely many processors approach only 4x
  • alpha = 0.05: limit 20x; 21 processors -> 10.5x, 57 -> 15x, 361
  • -> 19x
  • communication, data transfer, and cache coherence add costs beyond this ideal model

7

book highlights numerical simulation and video processing as parallel workloads

  • independent calculations can make the serial fraction small
  • benefit depends on the actual workload; these are examples, not an exhaustive list

8

interactive compression / decompression example:

  • lengthy computation must not freeze interface events or cancellation
  • one worker can compute while another handles the interface
  • author prefers separate processes with isolated memory for this design

9

creating threads does not itself create useful parallel work

  • threads that immediately wait for one another may add overhead without speedup

10

several independent event sources complicate sequential control flow

  • waiting for one client's next answer can delay every other client
  • each client may have its own logical request / response sequence

11

event-driven design: wait for an available event, identify its source, then handle it

  • handlers must not block waiting for a particular unrelated event
  • long computations must be split into manageable portions or moved elsewhere
  • explicitly retain each session's state / next expected action
  • some events only update state; further work waits for later events

12

one thread per event source can hide session state in thread execution state

  • blocked threads do not by themselves improve computational throughput
  • each thread consumes user-space and kernel resources
  • shared memory introduces synchronization responsibilities
  • author's preference here is explicit event handling

13

shared data: data accessible to several independently executing participants

  • participants may be processes or threads
  • shared objects may live in memory or in disk files

14

shared-data access requires deliberate coordination

  • critical section: logically connected work on shared data
  • mutual exclusion prevents conflicting critical sections from overlapping
  • simultaneous read-only access can be permitted

15

understanding the need for synchronization is part of writing threaded programs

  • using a thread API alone does not establish correctness

16

author's experience: programmers may use mutexes without being able to justify them

  • forthcoming examples explain concrete failures that a mutex must prevent

17

concurrency bugs may require rare execution interleavings

  • incorrect programs can appear to work for a long time
  • reproducing the same ordering of several threads is difficult
  • successful runs and ordinary debugging alone do not prove synchronization correct

18

Edward Lee's cited argument: threads introduce many possible execution orderings

  • programmer must restrict this nondeterminism to obtain predictable behavior

19

shared-data problems matter even when choosing not to use threads

  • needed to evaluate other concurrent programs
  • some domains, including multiprocessor kernels, inherently share state

20

independent programs can share data without belonging to one parallel application

  • mailbox example: delivery appends mail while clients read or delete it
  • database example: many users access and update the same records
  • when sharing is part of the problem itself, it cannot simply be designed away

Separate processes communicate between isolated address spaces,
whereas threads keep private stacks and registers inside one shared process
address space.

Amdahl speedup curves approach ceilings fixed by the sequential fraction,
even as the processor count continues to grow.

Parallel Execution

Threads, Processes, and Event Loops

A thread is an independently scheduled path of execution inside a process. Threads in one process use the same address space, so they can all reach the same global variables, heap objects, mappings, and file descriptors. Each thread still needs its own register state and stack.

Several different designs can make progress on more than one activity:

Design Memory relationship Main strength Main risk or cost
Sequential program One flow of control Deterministic and easiest to reason about Cannot overlap independent CPU work
Event loop One flow; session state stored explicitly Handles many mostly idle event sources efficiently Handlers must stay short and nonblocking
Multiple processes Separate address spaces by default Failure and memory isolation Explicit communication and data transfer
Multiple threads One shared address space Cheap access to common memory Accidental sharing, races, and difficult debugging

A thread per connection is sometimes used merely to remember where each client session stopped. That is not computational parallelism: most such threads sleep in input calls, and their stacks and kernel scheduling state become expensive session records. For many mostly idle connections, the event-driven state machines described in the previous chapter are often a better representation.

Threads are most convincing when all of these are true:

Responsiveness alone does not require shared-memory threads. A worker process can perform a long computation while a separate process or an event loop remains responsive, with the address-space boundary preventing many classes of accidental interference.

Amdahl's Law

If a fraction α\alpha of a computation remains sequential and the remaining fraction 1−α1-\alpha is divided perfectly among pp processors, the best possible speedup is

S(p)=1α+1−αp. S(p) = \frac{1}{\alpha + \frac{1-\alpha}{p}}.

The sequential fraction places a hard ceiling on speedup:

limp→∞S(p)=1α. \lim_{p \to \infty} S(p) = \frac{1}{\alpha}.

Sequential fraction α\alpha Processors pp Ideal speedup Absolute ceiling
0.250.25 10 3.083.08 4×4\times
0.250.25 100 3.883.88 4×4\times
0.050.05 21 10.5010.50 20×20\times
0.050.05 361 19.0019.00 20×20\times

These are ideal limits, not expected measurements. Real programs also pay for thread creation, scheduling, communication, cache coherence, memory bandwidth, synchronization, and load imbalance. Adding processors helps less and less as the sequential fraction begins to dominate.

Many programs are limited by network latency, storage, or memory bandwidth rather than arithmetic throughput. Measure the actual bottleneck before adding concurrency.

Shared Data and Race Conditions

Lost Updates and Inconsistent Snapshots

The expression

shared_count++;

looks like one action in C, but conceptually it contains several actions.

Suppose shared_count begins at 5 and two threads increment it:

Step Thread A Thread B Stored value
1 Loads 5 5
2 Loads 5 5
3 Computes and stores 6 6
4 Computes and stores 6 6

Both increments happened, but one was lost. The expected result was 7; the observed result is 6. This is a race condition: correctness depends on an unpredictable ordering of actions performed by independent participants. Making this one increment atomic would repair this example, but a single atomic instruction cannot by itself protect an invariant spanning several values or a longer calculation.

The same problem appears at a larger scale. If one transaction transfers money from account A to B while another uses an old balance from B, a later write can erase the first transfer. Even a read-only calculation can be wrong: summing a table while money moves from a row not yet read to a row already read can produce a total that never described the database at any instant.

Problem What went wrong
Lost update A new value was computed from a value another participant had replaced
Inconsistent snapshot Parts of one result came from mutually incompatible moments
Torn logical operation Other participants observed an invariant halfway through an update

Data naturally becomes stale over time; that alone is not always an error. The dangerous cases are computing a replacement from a stale version of the same state, or combining values that were never simultaneously valid.

The following teaching example deliberately makes the lost update easy to see. The assembly function copies its argument into a private register, increments that copy, pauses, and only then returns it:

Show the forced lost-update example
; abridged
inc:
        push    rbx
        mov     ebx, edi        ; copy the argument
        inc     ebx             ; compute the result privately

        ; nanosleep for two seconds

        mov     eax, ebx        ; return the saved result
        pop     rbx
        ret

Each worker calls it on the same field:

static void *worker(void *pointer)
{
    data_t *data = pointer;

    data->x = inc(data->x);     /* deliberately unprotected */
    return NULL;
}

If x starts at 5, both threads can pass 5 to inc, both can preserve 6 while paused, and both can eventually store 6. Putting a mutex around the entire call and assignment makes the result 7.

The pause only makes one bad interleaving reproducible; it does not create the race. Removing the pause can make the symptom rarer without making the code correct.

Detailed notes - 7.1.1: Stale Data and Data Integrity

1

two processes increment a shared integer initially equal to 5

  • intended final value: 7
  • each increment consists of load from memory, increment register, store to memory

2

some processors offer atomic memory arithmetic, e.g. suitable x86 LOCK operations

  • this does not make arbitrary multi-step updates atomic
  • incrementing a number stored as text still involves several operations
  • load/store architectures also illustrate the general problem

3

first process loads 5, then is interrupted

  • second process loads 5, increments to 6, and stores 6

4

first process resumes with its old register value 5

  • increments and stores 6, overwriting the other's update
  • final value 6 instead of 7 -> lost update
  • result depends on interleaving -> race condition

5

bank example: account balances 301 = $1000, 515 = $1500, 768 = $2000

  • transfer A: $100 from 301 to 768
  • transfer B: $200 from 768 to 515
  • correct balances after both: $900, $1700, $1900

6

transfer B reads balances, then pauses while A completes

  • A writes account 768 = $2100
  • B computes from the old $2000 and writes $1800
  • $100 disappears from the recorded total
  • reverse the unlucky ordering and account 768 can instead retain $200 too much

7

read-only summation can also race with transfers

  • sum has already visited destination account but has not visited source account
  • transfer occurs between the two reads
  • transferred money is counted in neither account
  • a reader can obtain an inconsistent result without modifying anything

8

common cause: computation uses input that became stale during the operation

  • increment overwrites a newer value
  • transfer computes from an obsolete balance
  • total combines balances observed at incompatible moments

9

data becoming old is not automatically an error

  • displayed results can legitimately describe a recent past state
  • problem: overwrite current data using a stale version of that same data
  • problem: combine values that were never simultaneously valid
  • latter case violates the integrity / consistency of the observed data
load shared_count -> add one -> store shared_count
A summation mixes destination-before-transfer with source-after-transfer and loses the transferred amount.
A read-only scan can still race. Open full size - Editable SVG
Interleaving two read-modify-write increments overwrites a completed update.
Two increments, one lost update. Open full size - Editable SVG
Tests & experiments (12 files) - 7.1.1: Stale Data and Data Integrity
Section testacconts (07-01-01)In catalog
MakefileMake / 21 lines
SRCMODULES = tools.c
OBJMODULES = $(SRCMODULES:.c=.o)

PROGRAMS = create read modify-00 modify-01 modify-02

CC = gcc
CFLAGS = -g -Wall -DLOCK=4

all: $(PROGRAMS)

%.o: %.c %.h
    $(CC) $(CFLAGS) -c $< -o $@

$(PROGRAMS): %: %.c $(OBJMODULES)
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)

ctags:
    ctags *.c *.h
create.cC / 20 lines
#include <unistd.h>

#include "tools.h"

int main(int argc, char **argv)
{
    int fd;
    int data[] = {
        301, 1000,
        515, 1500,
        768, 2000
    };

    check_arguments(argc, argv[0]);
    fd = open_file(argv[1], 'w');
    write(fd, data, sizeof(data));

    close(fd);
    return 0;
}
modify-00.cC / 30 lines
#include <stdio.h>
#include <unistd.h>
#include <err.h>

#include "tools.h"

enum {
    data_size = 6
};

int main(int argc, char **argv)
{
    int fd;
    int data;

    check_arguments(argc, argv[0]);
    fd = open_file(argv[1], 'm');

    lseek(fd, sizeof(int), SEEK_SET);
    read(fd, &data, sizeof(data));

    data += 100;
    lseek(fd, -sizeof(int), SEEK_CUR);
    write(fd, &data, sizeof(data));

    printf("%d\n", data);

    close(fd);
    return 0;
}
modify-01.cC / 36 lines
#include <stdlib.h>
#include <unistd.h>

#include "tools.h"

enum {
    sleep_time = 10
};

int main(int argc, char **argv)
{
    int fd, size;
    int from[2], to[2];

    check_arguments(argc, argv[0]);
    fd = open_file(argv[1], 'm');

    size = lseek(fd, 0, SEEK_END);
    lseek(fd, 0, SEEK_SET);

    lock(argv[1], fd, size);

    read_data(fd, from);
    lseek(fd, sizeof(from), SEEK_CUR);
    read_data(fd, to);

    lseek(fd, sizeof(from[0]), SEEK_SET);
    modify_data(fd, from, -100);
    lseek(fd, 3*sizeof(to[0]), SEEK_CUR);
    modify_data(fd, to, 100);

    unlock(argv[1], fd, size);

    close(fd);
    return 0;
}
modify-02.cC / 39 lines
#include <stdlib.h>
#include <unistd.h>

#include "tools.h"

enum {
    sleep_time = 10
};

int main(int argc, char **argv)
{
    int fd, i, rc, size;
    int from[2], to[2];

    check_arguments(argc, argv[0]);
    fd = open_file(argv[1], 'm');

    size = lseek(fd, 0, SEEK_END);
    lseek(fd, 0, SEEK_SET);

    lock(argv[1], fd, size);

    lseek(fd, 2*sizeof(from), SEEK_CUR);
    read_data(fd, from);
    lseek(fd, sizeof(from), SEEK_SET);
    read_data(fd, to);

    sleep(sleep_time);

    lseek(fd, 5*sizeof(from[0]), SEEK_SET);
    modify_data(fd, from, -200);
    lseek(fd, 3*sizeof(to[0]), SEEK_SET);
    modify_data(fd, to, 200);

    unlock(argv[1], fd, size);

    close(fd);
    return 0;
}
read.cC / 30 lines
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <err.h>

#include "tools.h"

enum {
    data_size = 6
};

int main(int argc, char **argv)
{
    int fd, i;
    int data[data_size];

    check_arguments(argc, argv[0]);

    fd = open_file(argv[1], 'r');

    read(fd, data, sizeof(data));
    for (i = 0; i < data_size; i++) {
        printf("%d ", data[i]);
        if (i % 2 == 1)
            printf("\n");
    }

    close(fd);
    return 0;
}
tools.cC / 145 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <err.h>
#include <string.h>
#include <sys/file.h>

#include "tools.h"

void *xmalloc(int size)
{
    void *p;

    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

void check_arguments(int argc, const char *program_name)
{
    if (argc < 2) {
        fprintf(stderr, "usage %s <file name>\n", program_name);
        exit(1);
    }
}

int open_file(const char *file_path, int mode)
{
    int fd;

    switch (mode) {
        case 'w':
            fd = open(file_path, O_WRONLY|O_CREAT|O_TRUNC, 0666);
            break;
        case 'e':
            fd = open(file_path, O_WRONLY|O_CREAT|O_EXCL, 0666);
            break;
        case 'm':
            fd = open(file_path, O_RDWR, 0666);
            break;
        case 'r':
            fd = open(file_path, O_RDONLY);
            break;
    }
    if (fd == -1)
        err(1, file_path);

    return fd;
}

void read_data(int fd, int *data)
{
    int rc;

    rc = read(fd, data, sizeof(data));
    if (rc != sizeof(data)) {
        fprintf(stderr, "wrong data read\n");
        exit(1);
    }
}

void modify_data(int fd, int *data, int diff)
{
    int original = data[1];
    data[1] += diff;
    write(fd, &data[1], sizeof(data[1]));
    printf("%d: %d -> %d\n", data[0], original, data[1]);
}

static char *file_lock_str(const char *file_name)
{
    char *file_lock;

    file_lock = xmalloc(strlen(file_name) + 6);
    strcpy(file_lock, file_name);
    strcat(file_lock, ".lock");

    return file_lock;
}

void file_lock(const char *file_path, int sleep_time)
{
    int fd;
    char *file_lock_name = file_lock_str(file_path);

    while (1) {
        fd = open(file_lock_name, O_WRONLY|O_CREAT|O_EXCL, 0666);
        if (fd != -1) {
            close(fd);
            break;
        }
        if (errno != EEXIST)
            err(1, file_lock_name);
        sleep(sleep_time);
    }
    free(file_lock_name);
}

void file_unlock(const char *file_path)
{
    char *file_lock_name = file_lock_str(file_path);
    unlink(file_lock_name);
    free(file_lock_name);
}

static void fcntl_lock(int fd, int type, int size)
{
    struct flock s;
    s.l_type = type;
    s.l_whence = SEEK_SET;
    s.l_start = 0;
    s.l_len = size;
    fcntl(fd, F_SETLKW, &s);
}

void lock(const char *file_name, int fd, int size)
{
#if LOCK == 1
    file_lock(file_name, 1);
#elif LOCK == 2
    flock(fd, LOCK_EX);
#elif LOCK == 3
    lockf(fd, F_LOCK, size);
#elif LOCK == 4
    fcntl_lock(fd, F_WRLCK, size);
#endif
}

void unlock(const char *file_name, int fd, int size)
{
#if LOCK == 1
    file_unlock(file_name);
#elif LOCK == 2
    flock(fd, LOCK_UN);
#elif LOCK == 3
    lockf(fd, F_ULOCK, size);
#elif LOCK == 4
    fcntl_lock(fd, F_UNLCK, size);
#endif
}
tools.hC / 12 lines
#ifndef TOOLS_H
#define TOOLS_H

void *xmalloc(int size);
void check_arguments(int argc, const char *program_name);
int open_file(const char *file_path, int mode);
void read_data(int fd, int *data);
void modify_data(int fd, int *data, int diff);
void lock(const char *file_name, int fd, int size);
void unlock(const char *file_name, int fd, int size);

#endif
Section testassembly (07-01-01)In catalog
MakefileMake / 28 lines
SRCMODULES = inc.asm
OBJMODULES = $(SRCMODULES:.asm=.o)
OBJMODULES := $(OBJMODULES:.c=.o)

PROGRAMS = incs

CC = gcc
CFLAGS = -g -Wall

ASM = nasm
AFLAGS = -g -f elf64

all: $(PROGRAMS)

%.o: %.asm %.h
    $(ASM) $(AFLAGS) $< -o $@

%.o: %.c %.h
    $(CC) $(CFLAGS) -c $< -o $@

$(PROGRAMS): %: %.c $(OBJMODULES)
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)

ctags:
    ctags *.c *.h
inc.asmAssembly / 24 lines
global inc

section .data

timespec:
    dq  2       ; seconds
    dq  0       ; nanoseconds

section .text

inc:
    push    rbx
    mov ebx, edi
    inc ebx

    mov rax, 35     ; SYS_nanosleep
    mov rdi, timespec
    xor esi, esi
    syscall

    mov eax, ebx
    pop rbx
    ret

inc.hC / 6 lines
#ifndef INC_H
#define INC_H

int inc(int x);

#endif
incs.cC / 65 lines
#include <stdio.h>
#include <pthread.h>
#include "inc.h"

enum {
    num_threads = 2
};

typedef struct {
    int x;
#if PROTECTION == 1
    pthread_mutex_t mut;
#endif
} data_t;

#if PROTECTION == 1
static void data_init(data_t *d)
{
    pthread_mutex_init(&d->mut, NULL);
}

static void data_destroy(data_t *d)
{
    pthread_mutex_destroy(&d->mut);
}
#endif

static void *worker(void *data)
{
    data_t *d = data;

    printf("%d\n", d->x);
#if PROTECTION == 1
    pthread_mutex_lock(&d->mut);
#endif
    d->x = inc(d->x);
#if PROTECTION == 1
    pthread_mutex_unlock(&d->mut);
#endif
    printf("%d\n", d->x);

    return NULL;
}

int main()
{
    int i;
    data_t d;
    pthread_t t[num_threads];
#if PROTECTION == 1
    data_init(&d);
#endif

    d.x = 5;
    for (i = 0; i < num_threads; i++)
        pthread_create(&t[i], NULL, worker, &d);

    for (i = 0; i < num_threads; i++)
        pthread_join(t[i], NULL);

#if PROTECTION == 1
    data_destroy(&d);
#endif
    return 0;
}

Critical Sections

A critical section is the complete region in which logically related work uses shared data. It begins before the first relevant shared value is read and ends only after the last dependent result has been produced and, when necessary, written back.

The boundary follows the invariant, not the number of source lines. A bank transfer, for example, must protect both account updates as one logical operation.

Two critical sections conflict when:

  1. they touch at least one common shared object, and
  2. at least one of them modifies that object.
Section A Section B Same data? May overlap safely?
Read Read Yes Usually yes
Read Write Yes No
Write Write Yes No
Any Any No Yes, unless another invariant links it

Mutual exclusion ensures that conflicting critical sections do not execute at the same time. The participants follow the locking protocol voluntarily: a mutex does not make the protected bytes physically inaccessible to code that ignores it.

A useful mutual-exclusion design should satisfy these requirements:

Correct locking must be applied consistently to every access covered by the invariant, including reads.

Detailed notes - 7.1.2: Mutual Exclusion and Critical Sections

1

serializing entire process lifetimes is usually too restrictive

  • a long-running server may access shared data only occasionally
  • protect the relevant operation, not every unrelated action of the process

2

keep related input consistent for the duration of a shared-data operation

  • updating shared storage: protection lasts through the final result write
  • producing an external report: result may legitimately become old afterward
  • read-only report needs a coherent set of inputs
  • once all required inputs have been safely copied, later private computation need not keep the shared data locked

3

critical section: logically connected manipulations of particular shared data

  • starts before the first relevant shared read
  • ends after required reads and all shared result writes
  • increment: load through store
  • transfer: first balance read through last updated balance write
  • summation: the complete protected scan

4

"critical section" can mean either:

  • a region of program code
  • the time interval during which that region executes

5

critical sections are defined relative to particular data

  • unrelated data need not share one exclusion mechanism
  • distinguish read-only sections from modifying sections

6

two critical sections conflict when:

  • both touch some of the same data
  • at least one modifies those common data
  • two read-only sections do not conflict

7

mutual exclusion: conflicting critical sections cannot execute simultaneously

  • its implementation must also avoid creating progress problems

8

participants follow synchronization rules voluntarily

  • access to shared memory is not physically blocked by an ordinary mutex
  • every cooperating program must obtain permission before using protected data
  • one participant ignoring the protocol can invalidate the whole scheme

9

requirements for the book's exclusion mechanisms:

  • never allow overlapping conflicting critical sections
  • do not assume relative process speeds or a particular processor count
  • a process outside its critical section must not prevent others from entering
  • avoid starvation: a participant must not wait forever while others proceed
  • avoid busy waiting where practical; blocked waiters should not waste CPU time
A transfer protects both reads and writes; a report can compute privately after a consistent copy.
Lock the whole invariant. Open full size - Editable SVG

Why an Ordinary Lock Variable Fails

This does not implement a lock:

while (available == 0) {
    /* wait */
}
available = 0;

/* critical section */

available = 1;

Two threads can both observe available == 1 before either stores 0. The test and update must be one indivisible, or atomic, operation.

Several historical approaches expose different requirements:

Approach What it demonstrates Why it is normally unsuitable
Ordinary lock variable Check-and-set must be atomic Two participants can both pass the check
Disable interrupts Some kernel operations need atomic regions Privileged, local to one CPU, and unsafe for user code
Strict alternation Exclusion alone is not enough An idle participant can prevent another from entering
Peterson's algorithm Software-only exclusion is possible Busy-waits and requires carefully defined atomic memory access
Hardware atomic operation Atomic read-modify-write closes the race Still busy-waits unless combined with blocking support

Textbook algorithms such as Peterson's assume a suitable memory model. In modern C, ordinary variables do not provide inter-thread synchronization; data races have undefined behavior. Use library synchronization primitives or correctly specified C atomic types, not volatile, for real programs.

Detailed notes - 7.1.3: Mutual Exclusion Using Variables

1

this subsection studies shared-variable algorithms with busy waiting

  • they illustrate synchronization logic without a blocking kernel primitive
  • real C implementations also require appropriate atomic operations / memory ordering

2

naive lock variable s: 1 = free, 0 = occupied

  • wait while s == 0
  • set s = 0; run critical section; set s = 1
  • separate test and assignment make this attempt incorrect

3

race: first process sees s == 1, then pauses before storing 0

  • second process also sees 1, sets 0, and enters
  • first resumes and enters too
  • both passed the test before either claimed the resource

4

testing availability and claiming the resource must form one atomic action

  • another participant must not intervene between these steps

5

disabling hardware interrupts is not a general user-space solution

  • long interrupt suppression disrupts device handling
  • accessing paged-out memory or performing I/O may require kernel activity
  • disabling interrupts on one CPU does not stop another CPU

6

busy waiting with interrupts disabled can freeze a uniprocessor system

  • resource owner cannot run to release the resource being awaited

7

ordinary user processes cannot disable interrupts

  • a bug or infinite loop could otherwise stop the system
  • kernel may briefly disable local interrupts as part of its own synchronization

8

strict alternation: shared turn chooses process 0 or process 1

  • process waits for its turn, executes its section, and hands over the turn
  • then performs unrelated work

9

alternation prevents simultaneous entry but can prevent useful progress

  • process cannot re-enter until the other returns and hands over its turn
  • other process may be busy with noncritical work
  • violates the rule that a participant outside its section must not block others

10

Peterson's algorithm: two participants, numbered 0 and 1

  • interested[2]: each participant's intent to enter / presence in its section
  • who_waits: participant that yields if both want to enter
  • generalized shared-variable algorithms include Lamport's bakery algorithm

11

participant i enters by:

  • interested[i] = true
  • who_waits = i
  • wait while who_waits == i AND interested[other]
  • proceed if the other yields or is no longer interested
  • on leaving: interested[i] = false

12

Peterson supplies enter_section and leave_section procedures

  • avoids the logical failures of naive locking and strict alternation
  • still busy-waits
  • correctness assumes atomic, properly ordered shared accesses; plain unsynchronized C variables are not a portable implementation
Separate test/store lets two threads enter; an atomic exchange grants only one owner.
Testing and claiming must be one operation. Open full size - Editable SVG
With both intent flags true, the last store to who_waits selects the waiting participant.
Peterson: the last contender yields. Open full size - Editable SVG
Tests & experiments (4 files) - 7.1.3: Mutual Exclusion Using Variables
Section test03 (07-01)In catalog
peterson-00.cC / 50 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <err.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int i, n, pid, *p, *interested, *var, *who_waits;

    n = 2;
    p = mmap(NULL, 5 * sizeof(*p), PROT_READ | PROT_WRITE,
             MAP_ANONYMOUS | MAP_SHARED, -1, 0);
    if (p == MAP_FAILED)
        err(1, "mmap");

    interested = p;
    who_waits = p + 2;
    var = p + 3;

    interested[0] = 0;
    interested[1] = 0;
    *who_waits = 0;
    *var = 0;

    for (i = 0; i < n; i++) {
        pid = fork();
        if (pid == -1)
            err(1, "fork");
        if (pid == 0) {
            while (1) {
                interested[i] = 1;
                *who_waits = i;
                while(*who_waits == i && interested[(i + 1) % n]) {}
                printf("Entering process %d, variable %d\n", getpid(), *var);
                (*var)++;
                printf("Exiting process %d, variable %d\n", getpid(), *var);
                sleep(4);
                interested[i] = 0;
            }
            exit(0);
        }
    }

    for (i = 0; i < n; i++)
        wait(NULL);

    return 0;
}
turns-00.cC / 49 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <err.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int i, n, pid, *p, *turn, *var;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <num processes>\n", argv[0]);
        exit(1);
    }
    n = atoi(argv[1]);

    p = mmap(NULL, 2 * sizeof(*p), PROT_READ | PROT_WRITE,
             MAP_ANONYMOUS | MAP_SHARED, -1, 0);
    if (p == MAP_FAILED)
        err(1, "mmap");

    turn = p;
    var = p + 1;

    *turn = 0;
    *var = 0;

    for (i = 0; i < n; i++) {
        pid = fork();
        if (pid == -1)
            err(1, "fork");
        if (pid == 0) {
            while (1) {
                while (*turn != i) {}
                (*var)++;
                printf("Turn: %d, changed variable: %d\n", i, *var);
                *turn = (i + 1) % n;
                sleep(1);
            }
            exit(0);
        }
    }

    for (i = 0; i < n; i++)
        wait(NULL);

    return 0;
}
variables-00.cC / 59 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <err.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int i, n, pid, *p, *locked, *var;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <num processes>\n", argv[0]);
        exit(1);
    }
    n = atoi(argv[1]);

    p = mmap(NULL, 2 * sizeof(*p), PROT_READ | PROT_WRITE,
             MAP_ANONYMOUS | MAP_SHARED, -1, 0);
    if (p == MAP_FAILED)
        err(1, "mmap");

    locked = p;
    var = p + 1;

    *locked = 0;
    *var = 0;

    for (i = 0; i < n; i++) {
        pid = fork();
        if (pid == -1)
            err(1, "fork");
        if (pid == 0) {
            while (1) {
                while (*locked == 1) {}
                *locked = 1;
                (*var)++;
                printf("Increase from process %d", getpid());
                *locked = 0;
                usleep(700000);
            }
            exit(0);
        }
    }


    while (1) {
        while (*locked == 1) {}
        *locked = 1;
        printf("Variable with value: %d\n", *var);
        *locked = 0;
        usleep(500000);
    }

    for (i = 0; i < n; i++)
        wait(NULL);

    return 0;
}
variables-01.cC / 61 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <err.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int i, n, pid, *p, *locked, *var;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <num processes>\n", argv[0]);
        exit(1);
    }
    n = atoi(argv[1]);

    p = mmap(NULL, 2 * sizeof(*p), PROT_READ | PROT_WRITE,
             MAP_ANONYMOUS | MAP_SHARED, -1, 0);
    if (p == MAP_FAILED)
        err(1, "mmap");

    locked = p;
    var = p + 1;

    *locked = 0;
    *var = 0;

    for (i = 0; i < n; i++) {
        pid = fork();
        if (pid == -1)
            err(1, "fork");
        if (pid == 0) {
            while (1) {
                while (*locked == 1) {}
                sleep(i + 1);
                *locked = 1;
                printf("Process: %d, before changing variable: %d\n", getpid(), *var);
                (*var)++;
                printf("Process: %d, after changing variable: %d\n", getpid(), *var);
                *locked = 0;
            }
            exit(0);
        }
    }

#if 0
    while (1) {
        while (*locked == 1) {}
        *locked = 1;
        printf("Variable with value: %d\n", *var);
        *locked = 0;
        sleep(1);
    }
#endif

    for (i = 0; i < n; i++)
        wait(NULL);

    return 0;
}

Mutexes

A mutex has two states, unlocked and locked, and an ownership rule: the thread that successfully locks it is responsible for unlocking it. A normal mutex is not recursive; trying to acquire it again while already owning it is a bug and may deadlock the caller.

Operation Normal result When it cannot be performed
lock Acquire an unlocked mutex and become its owner Block while another thread owns it
trylock Acquire an unlocked mutex and become its owner Return immediately and report that it is busy
unlock Release a mutex owned by the calling thread Misuse if it is unlocked or owned by someone else

The standard pattern is small and deliberately boring:

pthread_mutex_lock(&mutex);

/* read and update all state covered by this invariant */

pthread_mutex_unlock(&mutex);

Both acquisition and release must have the required atomic and memory-ordering effects. The lock does more than prevent simultaneous entry: it also makes writes made before an unlock visible to a thread that later acquires the same mutex.

Keep the protected interval no larger than correctness requires, but no smaller. A lock around only the final write does not help when the result was calculated from shared values that could change after they were read.

Detailed notes - 7.1.4: Mutexes

1

busy waiting repeatedly polls shared state while doing no useful work

  • preferable alternative: block until access may become available
  • later wake the waiter so it can acquire the resource
  • mutexes and semaphores provide the required synchronization abstractions

2

mutex: initially unlocked object with lock and unlock operations

  • blocking lock: acquire immediately if free, otherwise wait until acquisition succeeds
  • nonblocking try-lock: acquire if free, otherwise immediately report failure
  • once acquired, exactly one participant owns the mutex

3

mutex ownership rule: only the participant that locked it may unlock it

  • successful unlock releases ownership and makes further acquisition possible

4

absence of an ownership check does not permit another thread to unlock a mutex

  • implementation may leave misuse undetected
  • mutex ownership distinguishes a mutex from a binary semaphore

5

acquisition must be atomic with respect to other participants

  • no gap between observing "free" and claiming ownership
  • blocking may suspend the caller, but must not break the protocol

6

replace the naive lock variable with a real mutex

  • repeatedly trying a nonblocking lock preserves exclusion but still busy-waits
  • blocking version: lock(m); critical_section(); unlock(m)
  • the mutex's atomic acquisition prevents two successful owners at once

How Mutexes Block Efficiently

A processor instruction such as atomic exchange or compare-and-swap can change a lock word and report its old value as one indivisible action. That gives a fast uncontended path entirely in user space.

On Linux, low-level libraries can use the futex mechanism for the blocking and waking paths. Applications should normally use pthread_mutex_*, not call futex directly.

The teaching implementation below uses three lock-word values so the uncontended and contended paths can be distinguished:

Value Meaning
0 Unlocked
1 Locked, with no known sleeper
2 Locked or being acquired, with contention
Show the three-state futex algorithm
/* cmpxchg, xchg, and dec are atomic assembly routines. */
void lock(int *word)
{
    int old = cmpxchg(word, 0, 1);

    if (old != 0) {
        if (old != 2)
            old = xchg(word, 2);
        while (old != 0) {
            futex_wait(word, 2);
            old = xchg(word, 2);
        }
    }
}

void unlock(int *word)
{
    int old = dec(word);

    if (old != 1) {
        *word = 0;
        futex_wake(word, 1);
    }
}

The atomic helpers implement the read-modify-write operations with instructions such as lock cmpxchg and lock xadd. The first compare-and-swap is the cheap user-space path. A contender changes the state to 2 and sleeps only while the word still has the expected value; an unlock involving contention wakes one waiter.

This is architecture-specific study code, not a replacement for a POSIX mutex. A production implementation must also define memory ordering, handle system-call results and spurious wakeups, and obey all details of the platform ABI.

The performance lesson is important:

When lock contention dominates, a sequential design, partitioned data, message passing, or separate processes may be both simpler and faster.

Detailed notes - 7.1.5: Implementing Mutexes

1

kernel manages blocking and wakeup of scheduled processes / threads

  • sleep for an arbitrary interval cannot predict when a resource will become free
  • kernel synchronization can coordinate waiting and resource-state changes
  • local interrupt suppression alone is insufficient on multiple CPUs

2

entering the kernel for every acquisition and release can be expensive

  • synchronization cost can outweigh the work on a small protected object

3

atomic CPU operations allow an uncontended user-space fast path

  • x86 xchg with a memory operand atomically exchanges memory and a register
  • use the old value to determine whether acquisition succeeded

4

example representation: integer mutex, 1 = free, 0 = locked

  • put 0 in a register and exchange it with the mutex
  • old value 1 -> this operation acquired the lock
  • old value 0 -> already locked; caller must wait
  • release stores 1 with the ordering required by the implementation

5

simple assembly spinlock repeats exchange until the old value is 1

  • release restores 1
  • correct atomic claim, but repeated failure wastes CPU time
  • yielding to another thread between attempts can reduce spinning
  • yielding alone still does not provide a proper blocking wait

6

practical blocking implementations track contended locks and waiters

  • failed acquisition may ask the kernel to block the caller
  • releasing a lock with waiters may ask the kernel to wake one
  • lock operations can avoid kernel calls when nobody needs to block or wake

7

Linux futex supports waiting and waking around a shared user-space word

  • protocol must avoid races between changing the word and blocking
  • low-level futex programming is normally encapsulated by synchronization libraries

8

uncontended mutex operations often stay entirely in user space

  • contention introduces blocking, wakeups, scheduling, and extra kernel calls
  • keep critical sections short relative to useful independent work
  • frequent waiting can erase the benefit of parallel execution

An uncontended mutex stays on a user-space fast path;
a contended acquisition sleeps in a kernel wait queue and retries after an
unlock wakes a waiter.

Tests & experiments (10 files) - 7.1.5: Implementing Mutexes
Section testfutex (07-01-05)In catalog
MakefileMake / 28 lines
SRCMODULES = atomic.asm futex.c mutex.c
OBJMODULES = $(SRCMODULES:.asm=.o)
OBJMODULES := $(OBJMODULES:.c=.o)

PROGRAMS = main futex_demo

CC = gcc
CFLAGS = -g -Wall -O0

ASM = nasm
AFLAGS = -g -f elf64

all: $(PROGRAMS)

%.o: %.asm %.h
    $(ASM) $(AFLAGS) $< -o $@

%.o: %.c %.h
    $(CC) $(CFLAGS) -c $< -o $@

$(PROGRAMS): %: %.c $(OBJMODULES)
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)

ctags:
    ctags *.c *.h
atomic.asmAssembly / 20 lines
global xchg
global cmpxchg
global dec

section .text

xchg:
    mov     eax, esi
    xchg        dword [rdi], eax
    ret

cmpxchg:
    mov     eax, esi
    lock cmpxchg    dword [rdi], edx
    ret

dec:
    mov     eax, -1
    lock xadd   dword [rdi], eax
    ret
atomic.hC / 8 lines
#ifndef ATOMIC_H
#define ATOMIC_H

int xchg(int *var, int old);
int cmpxchg(int *var, int old, int new);
int dec(int *var);

#endif
event02.cC / 161 lines
#include <stdio.h>
#include <errno.h>

#include <pthread.h>
#include <unistd.h>
#include <sched.h>

#include <sys/syscall.h>
#include <linux/futex.h>


static int val = 0;

/* Lets main know Thread 3 has already read val. */
static volatile int thread3_read = 0;


/* futex_wait: sleep only if *addr == expected */
static int futex_wait(int *addr, int expected)
{
    return syscall(SYS_futex, addr, FUTEX_WAIT, expected, NULL, NULL, 0);
}


/* Wake all threads waiting on addr */
static int futex_wake(int *addr)
{
    return syscall(SYS_futex, addr, FUTEX_WAKE, 100, NULL, NULL, 0);
}


/* ------------------------------------------------ */
/* Thread 2                                         */
/* ------------------------------------------------ */

static void *thread2(void *arg)
{
    int oldval;

    (void)arg;

    printf("Thread 2: read val\n");

    oldval = __sync_fetch_and_add(&val, 0);

    printf("Thread 2: val = %d\n", oldval);

    printf("Thread 2: futex_wait\n");

    futex_wait(&val, oldval);

    printf("Thread 2: return from futex_wait\n");

    return NULL;
}


/* ------------------------------------------------ */
/* Thread 3                                         */
/* ------------------------------------------------ */

static void *thread3(void *arg)
{
    int oldval;
    int result;

    (void)arg;

    printf("Thread 3: read val\n");

    oldval = __sync_fetch_and_add(&val, 0);

    printf("Thread 3: val = %d\n", oldval);

    /*
     * Tell Thread 1 that Thread 3 has read val,
     * but has not called futex_wait yet.
     */
    __sync_lock_test_and_set(&thread3_read, 1);

    /*
     * Delay Thread 3.
     *
     * Thread 1 will change val and call
     * futex_wake while we are here.
     */
    usleep(500000);

    printf("Thread 3: futex_wait\n");

    errno = 0;

    result = futex_wait(&val, oldval);

    printf("Thread 3: return from futex_wait\n");

    if (result == -1 && errno == EAGAIN)
    {
        printf("Thread 3: EAGAIN - val changed, "
               "so the thread did not sleep\n");
    }

    return NULL;
}


/* ------------------------------------------------ */
/* Thread 1                                         */
/* ------------------------------------------------ */

int main(void)
{
    pthread_t t2;
    pthread_t t3;
    int woken;

    /*
     * Start Thread 2.
     */
    pthread_create(&t2, NULL, thread2, NULL);

    /*
     * Give Thread 2 some time to enter futex_wait.
     */
    usleep(100000);

    /*
     * Start Thread 3.
     */
    pthread_create(&t3, NULL, thread3, NULL);

    /*
     * Wait until Thread 3 has read val.
     */
    while (__sync_fetch_and_add(&thread3_read, 0) == 0)
    {
        sched_yield();
    }

    /*
     * main() is Thread 1.
     */

    printf("Thread 1: ++val\n");

    __sync_add_and_fetch(&val, 1);

    printf("Thread 1: val = %d\n",
           __sync_fetch_and_add(&val, 0));

    printf("Thread 1: futex_wake\n");

    woken = futex_wake(&val);

    printf("Thread 1: woke %d thread(s)\n", woken);

    pthread_join(t2, NULL);
    pthread_join(t3, NULL);

    return 0;
}
futex.cC / 15 lines
#include <linux/futex.h>
#include <sys/syscall.h>
#include <unistd.h>

#include "futex.h"

void futex_wait(int *futex, int expected)
{
    syscall(SYS_futex, futex, FUTEX_WAIT, expected, NULL, NULL, 0);
}

void futex_wake(int *futex, int num)
{
    syscall(SYS_futex, futex, FUTEX_WAKE, num, NULL, NULL, 0);
}
futex.hC / 7 lines
#ifndef FUTEX_H
#define FUTEX_H

void futex_wait(int *futex, int expected);
void futex_wake(int *futex, int num);

#endif
futex_demo.cC / 141 lines
/* futex_demo.c

   Usage: futex_demo [nloops]
                    (Default: 5)

   Demonstrate the use of futexes in a program where parent and child
   use a pair of futexes located inside a shared anonymous mapping to
   synchronize access to a shared resource: the terminal. The two
   processes each write 'num-loops' messages to the terminal and employ
   a synchronization protocol that ensures that they alternate in
   writing messages.
*/
#define _GNU_SOURCE
#include <err.h>
#include <errno.h>
#include <linux/futex.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>

static uint32_t *futex1, *futex2, *iaddr;

static int
futex(uint32_t *uaddr, int futex_op, uint32_t val,
      const struct timespec *timeout, uint32_t *uaddr2, uint32_t val3)
{
    return syscall(SYS_futex, uaddr, futex_op, val, timeout, uaddr2, val3);
}

/* Acquire the futex pointed to by 'futexp': wait for its value to
   become 1, and then set the value to 0. */

static void fwait(uint32_t *futexp)
{
    long            s;
    const uint32_t  one = 1;

    /* atomic_compare_exchange_strong(ptr, oldval, newval)
       atomically performs the equivalent of:

           if (*ptr == *oldval)
               *ptr = newval;

       It returns true if the test yielded true and *ptr was updated. */

    while (1) {

        /* Is the futex available? */
        if (atomic_compare_exchange_strong(futexp, &one, 0))
            break;      /* Yes */

        /* Futex is not available; wait. */

        s = futex(futexp, FUTEX_WAIT, 0, NULL, NULL, 0);
        if (s == -1 && errno != EAGAIN)
            err(EXIT_FAILURE, "futex-FUTEX_WAIT");
    }
}

/* Release the futex pointed to by 'futexp': if the futex currently
   has the value 0, set its value to 1 and then wake any futex waiters,
   so that if the peer is blocked in fwait(), it can proceed. */

static void
fpost(uint32_t *futexp)
{
    long            s;
    const uint32_t  zero = 0;

    /* atomic_compare_exchange_strong() was described
       in comments above. */

    if (atomic_compare_exchange_strong(futexp, &zero, 1)) {
        s = futex(futexp, FUTEX_WAKE, 1, NULL, NULL, 0);
        if (s  == -1)
            err(EXIT_FAILURE, "futex-FUTEX_WAKE");
    }
}

int
main(int argc, char *argv[])
{
    pid_t         childPid;
    unsigned int  nloops;

    setbuf(stdout, NULL);

    nloops = (argc > 1) ? atoi(argv[1]) : 5;

    /* Create a shared anonymous mapping that will hold the futexes.
       Since the futexes are being shared between processes, we
       subsequently use the "shared" futex operations (i.e., not the
       ones suffixed "_PRIVATE"). */

    /*  "sizeof(*iaddr) * 2" because 2 futexes */
    iaddr = mmap(NULL, sizeof(*iaddr) * 2, PROT_READ | PROT_WRITE,
                 MAP_ANONYMOUS | MAP_SHARED, -1, 0);
    if (iaddr == MAP_FAILED)
        err(EXIT_FAILURE, "mmap");

    futex1 = &iaddr[0];
    futex2 = &iaddr[1];

    *futex1 = 0;        /* State: unavailable */
    *futex2 = 1;        /* State: available */

    /* Create a child process that inherits the shared anonymous
       mapping. */

    childPid = fork();
    if (childPid == -1)
        err(EXIT_FAILURE, "fork");

    if (childPid == 0) {        /* Child */
        for (unsigned int j = 0; j < nloops; j++) {
            fwait(futex1);
            printf("Child  (%jd) %u\n", (intmax_t) getpid(), j);
            fpost(futex2);
        }

        exit(EXIT_SUCCESS);
    }

    /* Parent falls through to here. */

    for (unsigned int j = 0; j < nloops; j++) {
        fwait(futex2);
        printf("Parent (%jd) %u\n", (intmax_t) getpid(), j);
        fpost(futex1);
    }

    wait(NULL);

    exit(EXIT_SUCCESS);
}
main.cC / 48 lines
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

#include "mutex.h"

enum {
    num_threads = 3,
    pause_seconds = 1
};

typedef struct {
    int val;
    int x;
} data_t;

static void *worker_thread(void *data)
{
    data_t *d = data;

    lock(&d->val);
    d->x++;
    unlock(&d->val);

    return NULL;
}

int main()
{
    int i;
    pthread_t t;
    data_t d;

    d.val = 0;
    d.x = 0;

    for (i = 0; i < num_threads; i++)
        pthread_create(&t, NULL, worker_thread, &d);

    while (1) {
        lock(&d.val);
        printf("%d\n", d.x);
        unlock(&d.val);
        sleep(pause_seconds);
    }

    return 0;
}
mutex.cC / 30 lines
#include "atomic.h"
#include "futex.h"
#include "mutex.h"

void lock(int *val)
{
    int old;

    old = cmpxchg(val, 0, 1);
    if (old != 0) {
        if (old != 2)
            old = xchg(val, 2);
        while (old != 0) {
            futex_wait(val, 2);
            old = xchg(val, 2);
        }
    }
}

void unlock(int *val)
{
    int old;

    old = dec(val);
    if (old != 1) {
        *val = 0;
        futex_wake(val, 1);
    }
}

mutex.hC / 7 lines
#ifndef MUTEX_H
#define MUTEX_H

void lock(int *val);
void unlock(int *val);

#endif

Semaphores

A Dijkstra semaphore is a non-negative counter with two atomic operations:

Abstract operation POSIX name Effect
up / signal sem_post Increment the counter; wake a waiter if necessary
down / wait sem_wait Wait while zero, then decrement
try down sem_trywait Decrement if possible; otherwise return immediately

A semaphore initialized to NN can count NN available resource units. A semaphore initialized to 0 is useful for notification: a waiter sleeps until another participant announces an event with sem_post.

Mutexes and semaphores are related but not interchangeable:

Property Mutex Semaphore
State Locked or unlocked Non-negative count
Primary purpose Exclusive ownership of shared state Count resources or signal events
Ownership Yes; locker must unlock No; one participant may post for another
Usual initial value Unlocked Depends on available resources; often 0
More than one permit No Yes for a counting semaphore

A binary semaphore restricts the count to the role of 0 or 1, but it still does not acquire mutex ownership. Use a mutex to protect an invariant and a semaphore to represent resource availability or a handoff.

A counting semaphore can be built from an atomic compare-and-exchange and the Linux futex system call. try_down decrements the value only while it is positive; FUTEX_WAIT sleeps only if the value is still 0, so an up between the check and the sleep is never lost:

#ifndef SEMAPHORE_H
#define SEMAPHORE_H

typedef struct {
    int value;
    int waiters;
} semaphore_t;

void init(semaphore_t *s, int value);
void down(semaphore_t *s);
void up(semaphore_t *s);

#endif
static int try_down(semaphore_t *s)
{
    int value, old;

    value = s->value;
    while (value > 0) {
        old = cmpxchg(&s->value, value, value - 1);
        if (old == value)
            return 1;
        value = old;
    }

    return 0;
}

void down(semaphore_t *s)
{
    int success;

    success = try_down(s);
    if (success)
        return;

    inc(&s->waiters);
    while (1) {
        success = try_down(s);
        if (success) {
            dec(&s->waiters);
            return;
        }
        futex_wait(&s->value, 0);
    }
}

void up(semaphore_t *s)
{
    inc(&s->value);
    if (s->waiters > 0)
        futex_wake(&s->value, 1);
}

The atomic operations are three x86-64 instructions; lock makes each read-modify-write indivisible:

cmpxchg:
    mov     eax, esi
    lock cmpxchg    dword [rdi], edx
    ret

inc:
    mov     eax, 1
    lock xadd   dword [rdi], eax
    ret
void futex_wait(int *futex, int expected)
{
    syscall(SYS_futex, futex, FUTEX_WAIT, expected, NULL, NULL, 0);
}

A test with four threads incrementing a shared counter under the semaphore:

$ ./test_semaphore 4
2441
6543664
13113477
19702626
Detailed notes - 7.1.6: Dijkstra Semaphores

1

semaphore operations resemble mutex operations at first glance

  • one operation can block until another participant performs the opposite operation
  • both require atomic synchronization

2

mutex protects ownership of a shared resource

  • semaphore commonly counts available resources or signals events
  • one participant may legitimately wait on a semaphore that another posts

3

counting semaphore holds a nonnegative integer

  • up: add 1 and make an additional permit available
  • down: if positive, subtract 1 and continue
  • down at 0: block until a permit can be obtained
  • checking, consuming permits, and coordinating wakeups must be atomic

4

binary semaphore uses values 0 and 1

  • can enforce exclusion if initialized to 1 and used with balanced down / up
  • unlike a mutex, has no owner-only release rule
  • one process may perform down and another up

5

counting semaphore can represent several available resources

  • mathematical model allows any nonnegative count
  • implementations impose a finite maximum

6

historical attribution: semaphore abstraction is associated with Edsger Dijkstra

  • book also mentions an account crediting Carel Scholten with its counting extension

7

do not use mutex ownership violations as a substitute for semaphore signaling

  • missing runtime checks do not make misuse valid
  • roles should remain clear to readers
  • mutex normally starts unlocked; an event semaphore may start at zero

8

semaphore as resource counter:

  • wait before entering a section when the resource needed there is unavailable
  • example: no empty buffer slot or no produced item
  • binary event semaphore: wait until another participant signals permission

9

some implementations provide additional operations:

  • up(sem, n): add n permits
  • down(sem, n): wait for at least n, then consume n atomically
  • nonblocking down: immediately report unavailable permits
  • query/set count operations, often useful during initialization

10

System V semaphore arrays support compound atomic operations

  • example: add 2 to one semaphore and subtract 3 from another as one operation
  • can also wait for a semaphore to become zero

11

pipe illustration: one queued byte represents one available permit

  • up writes one byte; down reads one byte
  • reading an empty pipe blocks until another participant writes
  • finite pipe capacity bounds the count; writing a full pipe can block
  • every operation is a system call, so this is not an efficient mutex fast path
  • handle interrupted calls and endpoint lifetime in a real implementation
Two permits are consumed; a third participant waits until a posted permit can be consumed.
A semaphore counts unclaimed permits. Open full size - Editable SVG

Classic Synchronization Problems

Detailed notes - 7.2: Classical Mutual Exclusion Problems

1

examples use abstract C-like pseudocode

  • lock(m) / unlock(m): mutex operations
  • down(s) / up(s): semaphore operations
  • focus on synchronization logic, independent of process/thread API details

Producers and Consumers

Suppose producers place fixed-size items into a bounded buffer and consumers remove them. Three independent facts need representation:

Object Initial value Protects or represents
buffer_mutex unlocked Internal buffer structure
empty_slots NN Number of items producers may still insert
full_slots 00 Number of items consumers may currently remove
void produce_one(struct item item)
{
    sem_wait(&empty_slots);
    pthread_mutex_lock(&buffer_mutex);
    put_item(item);
    pthread_mutex_unlock(&buffer_mutex);
    sem_post(&full_slots);
}

struct item consume_one(void)
{
    struct item item;

    sem_wait(&full_slots);
    pthread_mutex_lock(&buffer_mutex);
    item = get_item();
    pthread_mutex_unlock(&buffer_mutex);
    sem_post(&empty_slots);
    return item;
}

The semaphores do not protect the buffer representation; the mutex does. The semaphores prevent entry when no useful operation is possible.

The order matters. If a consumer locks the buffer and then waits for a full slot, it can sleep while holding the very mutex a producer needs in order to create that slot. Wait for availability first, then acquire the mutex.

The following finite demonstration makes the bounded-buffer operations concrete. It uses a circular buffer for put_item and get_item.

Show a complete bounded-buffer example
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>

enum { capacity = 4, thread_count = 2, items_per_thread = 6 };

typedef struct {
    int slots[capacity];
    int head;
    int tail;
    sem_t empty_slots;
    sem_t full_slots;
    pthread_mutex_t mutex;
} queue_t;

typedef struct {
    queue_t *queue;
    int id;
} worker_args_t;

static void queue_put(queue_t *queue, int value)
{
    sem_wait(&queue->empty_slots);
    pthread_mutex_lock(&queue->mutex);

    queue->slots[queue->tail] = value;
    queue->tail = (queue->tail + 1) % capacity;

    pthread_mutex_unlock(&queue->mutex);
    sem_post(&queue->full_slots);
}

static int queue_get(queue_t *queue)
{
    int value;

    sem_wait(&queue->full_slots);
    pthread_mutex_lock(&queue->mutex);

    value = queue->slots[queue->head];
    queue->head = (queue->head + 1) % capacity;

    pthread_mutex_unlock(&queue->mutex);
    sem_post(&queue->empty_slots);
    return value;
}

static void *producer(void *pointer)
{
    worker_args_t *args = pointer;
    int i;

    for (i = 0; i < items_per_thread; i++)
        queue_put(args->queue, 100 * args->id + i);
    return NULL;
}

static void *consumer(void *pointer)
{
    worker_args_t *args = pointer;
    int i;

    for (i = 0; i < items_per_thread; i++) {
        int value = queue_get(args->queue);
        printf("consumer %d <- %d\n", args->id, value);
    }
    return NULL;
}

int main(void)
{
    queue_t queue = { .head = 0, .tail = 0 };
    pthread_t producers[thread_count];
    pthread_t consumers[thread_count];
    worker_args_t args[thread_count];
    int i;

    sem_init(&queue.empty_slots, 0, capacity);
    sem_init(&queue.full_slots, 0, 0);
    pthread_mutex_init(&queue.mutex, NULL);

    for (i = 0; i < thread_count; i++) {
        args[i].queue = &queue;
        args[i].id = i;
        pthread_create(&producers[i], NULL, producer, &args[i]);
        pthread_create(&consumers[i], NULL, consumer, &args[i]);
    }

    for (i = 0; i < thread_count; i++) {
        pthread_join(producers[i], NULL);
        pthread_join(consumers[i], NULL);
    }

    pthread_mutex_destroy(&queue.mutex);
    sem_destroy(&queue.full_slots);
    sem_destroy(&queue.empty_slots);
    return 0;
}
cc -Wall -Wextra -pthread producer-consumer.c -o producer-consumer
./producer-consumer

The values may be printed in different orders on different runs, but exactly twelve values are consumed and no buffer slot is overwritten before its previous value is removed. Error checks are omitted here to keep the synchronization protocol visible.

Detailed notes - 7.2.1: Producers and Consumers

1

producers generate data for later processing

  • possible sources: sensors, network input, user interaction, computation

2

consumers process the data prepared by producers

3

bounded shared buffer holds N fixed-size items

  • buffer operations require mutual exclusion
  • example protects the entire buffer as one shared object

4

two resource shortages must block useful work:

  • consumer wants an item, but buffer is empty
  • producer has an item, but buffer is full
  • each waits for an operation by the opposite kind of participant

5

repeatedly locking, checking, unlocking, and retrying is busy waiting

  • long retry intervals delay available work
  • short intervals waste CPU and cause lock contention
  • no arbitrary polling interval solves the underlying coordination problem

6

counting semaphores prevent entry until a needed resource is available

  • empty: free slots; initially N for an empty buffer
  • full: available items; initially 0
  • mutex m separately protects changes to buffer contents and bookkeeping

7

put_data / get_data perform only buffer manipulation

  • assume caller already owns m
  • assume a suitable slot / item has already been reserved
  • find slot, copy data, update buffer bookkeeping

8

producer:

  • prepare item; down(empty); lock(m); put_data(); unlock(m); up(full)
  • consumer: down(full); lock(m); get_data(); unlock(m); up(empty); process item
  • semaphore waits happen before taking the mutex
  • semaphores count resources; mutex provides exclusion
  • item preparation / processing happens outside the buffer's critical section

A producer waits for an empty-slot permit before inserting,
a consumer waits for a full-slot permit before removing,
and a mutex protects the bounded buffer during either operation.

Correct producer/consumer ordering permits progress; waiting for space while holding the mutex deadlocks a full buffer.
Reserve the buffer resource before taking its mutex. Open full size - Editable SVG
Examples & tests (18 files) - 7.2.1: Producers and Consumers
Book exampleBook example: prod_cons.cIn catalog
prod_cons.cC / 126 lines
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <math.h>

#define BUFFER_SIZE 4096
#define CONSUMERS_COUNT 10
#define PAUSE_LENGTH 5

struct buf_str {
    int count;
    double values[BUFFER_SIZE];
} buffer;

void init_buffer()
{
    buffer.count = 0;
}
void put_buffer_item(double v)
{
    buffer.values[buffer.count] = v;
    buffer.count++;
}

double get_buffer_item()
{
    buffer.count--;
    return buffer.values[buffer.count];
}

sem_t buf_empty;
sem_t buf_full;
pthread_mutex_t buf_mutex = PTHREAD_MUTEX_INITIALIZER;

double grand_total = 0;
long grand_count = 0;
pthread_mutex_t grand_mutex = PTHREAD_MUTEX_INITIALIZER;

sem_t producers_count, data_pieces;

void *producer_thread(void *v)
{             /* v points to the name of the source */
    double val;
    FILE *f = fopen((char*)v, "r");
    if(!f) {
        perror((char*)v);
        sem_wait(&producers_count);
        return NULL;
    }
    while(!feof(f)) {
        if(1 != fscanf(f, "%lf", &val))
            continue;
        sem_post(&data_pieces);
        sem_wait(&buf_empty);     /* the Producer */
        pthread_mutex_lock(&buf_mutex);
        put_buffer_item(val);
        pthread_mutex_unlock(&buf_mutex);
        sem_post(&buf_full);      /*  -------     */
    }
    sem_wait(&producers_count);
    return NULL;
}

void *consumer_thread(void *ignored)
{
    for(;;) {
        double val;
        sem_wait(&buf_full);      /* The Consumer */
        pthread_mutex_lock(&buf_mutex);
        val = get_buffer_item();
        pthread_mutex_unlock(&buf_mutex);
        sem_post(&buf_empty);     /*   -------    */
        val = log(val);
        pthread_mutex_trylock(&grand_mutex);
        grand_total += val;
        grand_count++;
        pthread_mutex_unlock(&grand_mutex);
        sem_wait(&data_pieces);
    }
}

int main(int argc, char **argv)
{
    pthread_t thr;
    int i;
    init_buffer();
    sem_init(&buf_empty, 0, BUFFER_SIZE);
    sem_init(&buf_full, 0, 0);
    sem_init(&producers_count, 0, 0);
    sem_init(&data_pieces, 0, 0);
    for(i = 1; i < argc; i++) {
        sem_post(&producers_count);
        pthread_create(&thr, NULL, producer_thread, (void*)argv[i]);
    }
    for(i = 0; i < CONSUMERS_COUNT; i++)
        pthread_create(&thr, NULL, consumer_thread, NULL);
    usleep(100000);

    for(;;) {
        int p_c, d_p;
        double gt;
        long gc;
        pthread_mutex_lock(&grand_mutex);
        gt = grand_total;
        gc = grand_count;
        grand_total = 0;
        grand_count = 0;
        sem_getvalue(&producers_count, &p_c);
        sem_getvalue(&data_pieces, &d_p);
        pthread_mutex_unlock(&grand_mutex);
        if(gc > 0)
            printf("total average: %f (sum = %f; count = %ld)\n",
                   gt/((double)gc), gt, gc);
        else
            printf("No data yet...\n");
        printf("%d producers still active\n", p_c);
        printf("%d data pieces being processed\n", d_p);
        if(p_c == 0 && d_p == 0) {
            printf("No more producers, no more data\n");
            break;
        }
        sleep(PAUSE_LENGTH);
    }
    return 0;
}
Section test01 (07-02)In catalog
generate-data-02.cC / 29 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char **argv)
{
    int i, n, x;

    srand(time(NULL));
    if (argc < 3) {
        fprintf(stderr, "Usage %s <file name> <num data> \n", argv[0]);
        return 1;
    }
    n = atoi(argv[2]);

    FILE *f = fopen(argv[1], "w");
    if (!f) {
        perror("fopen");
        return 1;
    }

    for (i = 0; i < n; i++) {
        x = rand();
        fprintf(f, "%d\n", x);
    }

    fclose(f);
    return 0;
}
producer-consumer-01.cC / 86 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

typedef struct {
    sem_t empty;
    sem_t full;
    pthread_mutex_t mutex;
    int value;
} data_t;

static void *producer(void *data)
{
    data_t *d = data;

    while (1) {
        sem_wait(&d->empty);
        pthread_mutex_lock(&d->mutex);
        d->value++;
        usleep(100000);
        pthread_mutex_unlock(&d->mutex);
        sem_post(&d->full);
    }

    return NULL;
}

static void *consumer(void *data)
{
    data_t *d = data;

    while (1) {
        sem_wait(&d->full);
        pthread_mutex_lock(&d->mutex);
        d->value--;
        usleep(100000);
        pthread_mutex_unlock(&d->mutex);
        sem_post(&d->empty);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i, n;
    pthread_t *tc, *tp;
    data_t *d;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
        return 1;
    }
    n = atoi(argv[1]);

    d = malloc(n * sizeof(*d));
    tc = malloc(n * sizeof(*tc));
    tp = malloc(n * sizeof(*tp));
    for (i = 0; i < n; i++) {
        sem_init(&d[i].empty, 0, n);
        sem_init(&d[i].full, 0, 0);
        pthread_mutex_init(&d[i].mutex, NULL);
        d[i].value = 0;
        pthread_create(&tp[i], NULL, producer, &d[i]);
        pthread_create(&tc[i], NULL, consumer, &d[i]);
    }

    while (1) {
        for (i = 0; i < n; i++)
            printf("%2d ", d[i].value);
        printf("\n");
        usleep(200000);
    }

    for (i = 0; i < n; i++) {
        pthread_join(tc[i], NULL);
        pthread_join(tp[i], NULL);
        sem_destroy(&d[i].empty);
        sem_destroy(&d[i].full);
        pthread_mutex_destroy(&d[i].mutex);
    }

    return 0;
}
producer-consumer-02.cC / 126 lines
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <math.h>

#define BUFFER_SIZE 4096
#define CONSUMERS_COUNT 10
#define PAUSE_LENGTH 5

struct buf_str {
    int count;
    double values[BUFFER_SIZE];
} buffer;

void init_buffer()
{
    buffer.count = 0;
}
void put_buffer_item(double v)
{
    buffer.values[buffer.count] = v;
    buffer.count++;
}

double get_buffer_item()
{
    buffer.count--;
    return buffer.values[buffer.count];
}

sem_t buf_empty;
sem_t buf_full;
pthread_mutex_t buf_mutex = PTHREAD_MUTEX_INITIALIZER;

double grand_total = 0;
long grand_count = 0;
pthread_mutex_t grand_mutex = PTHREAD_MUTEX_INITIALIZER;

sem_t producers_count, data_pieces;

void *producer_thread(void *v)
{             /* v points to the name of the source */
    double val;
    FILE *f = fopen((char*)v, "r");
    if(!f) {
        perror((char*)v);
        sem_wait(&producers_count);
        return NULL;
    }
    while(!feof(f)) {
        if(1 != fscanf(f, "%lf", &val))
            continue;
        sem_post(&data_pieces);
        sem_wait(&buf_empty);     /* the Producer */
        pthread_mutex_lock(&buf_mutex);
        put_buffer_item(val);
        pthread_mutex_unlock(&buf_mutex);
        sem_post(&buf_full);      /*  -------     */
    }
    sem_wait(&producers_count);
    return NULL;
}

void *consumer_thread(void *ignored)
{
    for(;;) {
        double val;
        sem_wait(&buf_full);      /* The Consumer */
        pthread_mutex_lock(&buf_mutex);
        val = get_buffer_item();
        pthread_mutex_unlock(&buf_mutex);
        sem_post(&buf_empty);     /*   -------    */
        val = log(val);
        pthread_mutex_lock(&grand_mutex);
        grand_total += val;
        grand_count++;
        pthread_mutex_unlock(&grand_mutex);
        sem_wait(&data_pieces);
    }
}

int main(int argc, char **argv)
{
    pthread_t thr;
    int i;
    init_buffer();
    sem_init(&buf_empty, 0, BUFFER_SIZE);
    sem_init(&buf_full, 0, 0);
    sem_init(&producers_count, 0, 0);
    sem_init(&data_pieces, 0, 0);
    for(i = 1; i < argc; i++) {
        sem_post(&producers_count);
        pthread_create(&thr, NULL, producer_thread, (void*)argv[i]);
    }
    for(i = 0; i < CONSUMERS_COUNT; i++)
        pthread_create(&thr, NULL, consumer_thread, NULL);
    usleep(100000);

    for(;;) {
        int p_c, d_p;
        double gt;
        long gc;
        pthread_mutex_lock(&grand_mutex);
        gt = grand_total;
        gc = grand_count;
        grand_total = 0;
        grand_count = 0;
        sem_getvalue(&producers_count, &p_c);
        sem_getvalue(&data_pieces, &d_p);
        pthread_mutex_unlock(&grand_mutex);
        if(gc > 0)
            printf("total average: %f (sum = %f; count = %ld)\n",
                   gt/((double)gc), gt, gc);
        else
            printf("No data yet...\n");
        printf("%d producers still active\n", p_c);
        printf("%d data pieces being processed\n", d_p);
        if(p_c == 0 && d_p == 0) {
            printf("No more producers, no more data\n");
            break;
        }
        sleep(PAUSE_LENGTH);
    }
    return 0;
}
producer-consumer-03.cC / 196 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <math.h>
#include <string.h>

enum {
    buf_size = 4096,
    num_consumers = 4
};

typedef struct {
    int i;
    double d[buf_size];
} buffer_t;

static void buf_init(buffer_t *buf) {
    buf->i = 0;
}

static void buf_push(buffer_t *buf, double x) {
    buf->d[buf->i] = x;
    buf->i++;
}

static double buf_pop(buffer_t *buf) {
    buf->i--;
    return buf->d[buf->i];
}

typedef struct {
    sem_t data_sem;
    sem_t empty;
    sem_t full;
    const char *file_name;
    pthread_mutex_t buf_mutex;
    buffer_t buf;
    pthread_mutex_t sum_mutex;
    double sum;
    long count;
    pthread_mutex_t num_producers_mutex;
    int num_producers;
    pthread_mutex_t data_pieces_mutex;
    int data_pieces;
    int done;
} data_t;

static void data_init(data_t *d)
{
    sem_init(&d->data_sem, 0, 0);
    sem_init(&d->empty, 0, buf_size);
    sem_init(&d->full, 0, 0);
    pthread_mutex_init(&d->buf_mutex, NULL);
    buf_init(&d->buf);
    pthread_mutex_init(&d->sum_mutex, NULL);
    d->sum = 0;
    d->count = 0;
    pthread_mutex_init(&d->num_producers_mutex, NULL);
    d->num_producers = 0;
    pthread_mutex_init(&d->data_pieces_mutex, NULL);
    d->data_pieces = 0;
    d->done = 0;
}

static void data_destroy(data_t *d)
{
    sem_destroy(&d->data_sem);
    sem_destroy(&d->empty);
    sem_destroy(&d->full);
    pthread_mutex_destroy(&d->buf_mutex);
    pthread_mutex_destroy(&d->sum_mutex);
    pthread_mutex_destroy(&d->num_producers_mutex);
    pthread_mutex_destroy(&d->data_pieces_mutex);
}

static void *producer(void *data)
{
    data_t *d = data;
    char *file_name = strdup(d->file_name);
    sem_post(&d->data_sem);
    double x;
    FILE *f;

    f = fopen(file_name, "r");
    if (!f) {
        perror(file_name);
        goto cleanup;
    }
    while (fscanf(f, "%lf", &x) == 1) {
        pthread_mutex_lock(&d->data_pieces_mutex);
        d->data_pieces++;
        pthread_mutex_unlock(&d->data_pieces_mutex);
        sem_wait(&d->empty);
        pthread_mutex_lock(&d->buf_mutex);
        buf_push(&d->buf, x);
        pthread_mutex_unlock(&d->buf_mutex);
        sem_post(&d->full);
    }
    fclose(f);

cleanup:
    pthread_mutex_lock(&d->num_producers_mutex);
    d->num_producers--;
    pthread_mutex_unlock(&d->num_producers_mutex);
    free(file_name);
    return NULL;
}

static void *consumer(void *data)
{
    double x;
    data_t *d = data;

    while (1) {
        sem_wait(&d->full);
        pthread_mutex_lock(&d->buf_mutex);
        if (d->done == 1 && d->buf.i == 0) {
            pthread_mutex_unlock(&d->buf_mutex);
            break;
        }
        x = buf_pop(&d->buf);
        pthread_mutex_unlock(&d->buf_mutex);
        sem_post(&d->empty);
        x = log(x);
        pthread_mutex_lock(&d->sum_mutex);
        d->sum += x;
        d->count++;
        pthread_mutex_unlock(&d->sum_mutex);
        pthread_mutex_lock(&d->data_pieces_mutex);
        d->data_pieces--;
        pthread_mutex_unlock(&d->data_pieces_mutex);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i, n;
    pthread_t *tc, *tp;
    data_t d;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <file name> ... \n", argv[0]);
        return 1;
    }
    data_init(&d);

    n = argc - 1;
    d.num_producers = n;
    tp = malloc(n * sizeof(*tp));
    for (i = 0; i < n; i++) {
        d.file_name = argv[i+1];
        pthread_create(&tp[i], NULL, producer, &d);
        sem_wait(&d.data_sem);
    }

    tc = malloc(num_consumers * sizeof(*tc));
    for (i = 0; i < num_consumers; i++)
        pthread_create(&tc[i], NULL, consumer, &d);

    while (1) {
        pthread_mutex_lock(&d.sum_mutex);
        if(d.count > 0)
            printf("total average: %f (sum = %f; count = %ld)\n",
                   d.sum/((double) d.count), d.sum, d.count);
        pthread_mutex_unlock(&d.sum_mutex);
        pthread_mutex_lock(&d.num_producers_mutex);
        pthread_mutex_lock(&d.data_pieces_mutex);
        if (d.num_producers == 0 && d.data_pieces == 0)
            break;
        pthread_mutex_unlock(&d.data_pieces_mutex);
        pthread_mutex_unlock(&d.num_producers_mutex);
        usleep(200000);
    }
    pthread_mutex_unlock(&d.data_pieces_mutex);
    pthread_mutex_unlock(&d.num_producers_mutex);

    pthread_mutex_lock(&d.buf_mutex);
    d.done = 1;
    pthread_mutex_unlock(&d.buf_mutex);
    for (i = 0; i < num_consumers; i++)
        sem_post(&d.full);

    for (i = 0; i < n; i++)
        pthread_join(tp[i], NULL);

    for (i = 0; i < num_consumers; i++)
        pthread_join(tc[i], NULL);

    data_destroy(&d);

    return 0;
}
test.cC / 24 lines
#include <stdio.h>

typedef struct {
    int x;
    int y;
} data_t;

static void data_init(data_t *d)
{
    d->x = 1;
    d->y = 1;
}

int main()
{
    data_t d;
    double x;
    data_init(&d);

    x = 5.12;
    printf("%d %d %f\n", d.x, d.y, x);

    return 0;
}
Section testproducer-consumer-00 (07-02-01)In catalog
MakefileMake / 28 lines
SRCMODULES = atomic.asm futex.c mutex.c semaphore.c
OBJMODULES = $(SRCMODULES:.asm=.o)
OBJMODULES := $(OBJMODULES:.c=.o)

PROGRAMS = test_mutex test_semaphore main

CC = gcc
CFLAGS = -g -Wall -O0

ASM = nasm
AFLAGS = -g -f elf64

all: $(PROGRAMS)

%.o: %.asm %.h
    $(ASM) $(AFLAGS) $< -o $@

%.o: %.c %.h
    $(CC) $(CFLAGS) -c $< -o $@

$(PROGRAMS): %: %.c $(OBJMODULES)
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)

ctags:
    ctags *.c *.h
atomic.asmAssembly / 26 lines
global xchg
global cmpxchg
global dec
global inc

section .text

xchg:
    mov     eax, esi
    xchg        dword [rdi], eax
    ret

cmpxchg:
    mov     eax, esi
    lock cmpxchg    dword [rdi], edx
    ret

dec:
    mov     eax, -1
    lock xadd   dword [rdi], eax
    ret

inc:
    mov     eax, 1
    lock xadd   dword [rdi], eax
    ret
atomic.hC / 9 lines
#ifndef ATOMIC_H
#define ATOMIC_H

int xchg(int *var, int old);
int cmpxchg(int *var, int old, int new);
int dec(int *var);
int inc(int *var);

#endif
futex.cC / 15 lines
#include <linux/futex.h>
#include <sys/syscall.h>
#include <unistd.h>

#include "futex.h"

void futex_wait(int *futex, int expected)
{
    syscall(SYS_futex, futex, FUTEX_WAIT, expected, NULL, NULL, 0);
}

void futex_wake(int *futex, int num)
{
    syscall(SYS_futex, futex, FUTEX_WAKE, num, NULL, NULL, 0);
}
futex.hC / 7 lines
#ifndef FUTEX_H
#define FUTEX_H

void futex_wait(int *futex, int expected);
void futex_wake(int *futex, int num);

#endif
main.cC / 78 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "mutex.h"
#include "semaphore.h"

typedef struct {
    semaphore_t empty;
    semaphore_t full;
    int mutex;
    int value;
} data_t;

static void *producer(void *data)
{
    data_t *d = data;

    while (1) {
        down(&d->empty);
        lock(&d->mutex);
        d->value++;
        usleep(100000);
        unlock(&d->mutex);
        up(&d->full);
    }

    return NULL;
}

static void *consumer(void *data)
{
    data_t *d = data;

    while (1) {
        down(&d->full);
        lock(&d->mutex);
        d->value--;
        usleep(100000);
        unlock(&d->mutex);
        up(&d->empty);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i, n;
    pthread_t t;
    data_t *d;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
        return 1;
    }
    n = atoi(argv[1]);

    d = malloc(n * sizeof(*d));
    for (i = 0; i < n; i++) {
        init(&d[i].empty, n);
        init(&d[i].full, 0);
        d[i].mutex = 0;
        d[i].value = 0;
        pthread_create(&t, NULL, producer, &d[i]);
        pthread_create(&t, NULL, consumer, &d[i]);
    }

    while (1) {
        for (i = 0; i < n; i++)
            printf("%2d ", d[i].value);
        printf("\n");
        usleep(500000);
    }

    return 0;
}
mutex.cC / 30 lines
#include "atomic.h"
#include "futex.h"
#include "mutex.h"

void lock(int *m)
{
    int old;

    old = cmpxchg(m, 0, 1);
    if (old != 0) {
        if (old != 2)
            old = xchg(m, 2);
        while (old != 0) {
            futex_wait(m, 2);
            old = xchg(m, 2);
        }
    }
}

void unlock(int *m)
{
    int old;

    old = dec(m);
    if (old != 1) {
        *m = 0;
        futex_wake(m, 1);
    }
}

mutex.hC / 7 lines
#ifndef MUTEX_H
#define MUTEX_H

void lock(int *m);
void unlock(int *m);

#endif
semaphore.cC / 51 lines
#include "atomic.h"
#include "futex.h"
#include "semaphore.h"

void init(semaphore_t *s, int value)
{
    s->value = value;
    s->waiters = 0;
}

static int try_down(semaphore_t *s)
{
    int value, old;

    value = s->value;
    while (value > 0) {
        old = cmpxchg(&s->value, value, value - 1);
        if (old == value)
            return 1;
        value = old;
    }

    return 0;
}

void down(semaphore_t *s)
{
    int success;

    success = try_down(s);
    if (success)
        return;

    inc(&s->waiters);
    while (1) {
        success = try_down(s);
        if (success) {
            dec(&s->waiters);
            return;
        }
        futex_wait(&s->value, 0);
    }
}

void up(semaphore_t *s)
{
    inc(&s->value);
    if (s->waiters > 0)
        futex_wake(&s->value, 1);
}

semaphore.hC / 13 lines
#ifndef SEMAPHORE_H
#define SEMAPHORE_H

typedef struct {
    int value;
    int waiters;
} semaphore_t;

void init(semaphore_t *s, int value);
void down(semaphore_t *s);
void up(semaphore_t *s);

#endif
test_mutex.cC / 54 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "mutex.h"

enum {
    pause_seconds = 1
};

typedef struct {
    int val;
    int x;
} data_t;

static void *worker_thread(void *data)
{
    data_t *d = data;

    while (1) {
        lock(&d->val);
        d->x++;
        unlock(&d->val);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i, n;
    pthread_t t;
    data_t d;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
        return 1;
    }
    n = atoi(argv[1]);

    d.val = 0;
    d.x = 0;

    for (i = 0; i < n; i++)
        pthread_create(&t, NULL, worker_thread, &d);

    while (1) {
        printf("%d\n", d.x);
        sleep(pause_seconds);
    }

    return 0;
}
test_semaphore.cC / 56 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "semaphore.h"

enum {
    pause_seconds = 1
};

typedef struct {
    semaphore_t s;
    int x;
} data_t;

static void *worker_thread(void *data)
{
    data_t *d = data;

    while (1) {
        down(&d->s);
        d->x++;
        up(&d->s);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i, n;
    pthread_t t;
    data_t d;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
        return 1;
    }
    n = atoi(argv[1]);

    init(&d.s, 1);
    d.x = 0;

    for (i = 0; i < n; i++)
        pthread_create(&t, NULL, worker_thread, &d);

    while (1) {
        down(&d.s);
        printf("%d\n", d.x);
        up(&d.s);
        sleep(pause_seconds);
    }

    return 0;
}

Dining Philosophers, Deadlock, and Livelock

Five philosophers share five forks, one between each neighboring pair. Each philosopher needs both adjacent forks to eat. If all five acquire their left fork and then wait for their right fork, every participant waits for a resource held by another participant. No one can make progress: this is deadlock.

The same structure needs only two threads and two locks:

/* Thread A */                  /* Thread B */
pthread_mutex_lock(&m1);        pthread_mutex_lock(&m2);
pthread_mutex_lock(&m2);        pthread_mutex_lock(&m1);

It is also possible to deadlock without mutexes. If a parent calls wait before draining a pipe while its child fills that pipe, the child waits for free pipe space and the parent waits for the child to exit.

The following small experiment makes that less obvious cycle visible:

Show a deadlock caused by a full pipe
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
    char buffer[100];
    int pipe_fd[2];
    int child;
    int count;

    pipe(pipe_fd);
    child = fork();
    if (child == 0) {
        dup2(pipe_fd[1], STDOUT_FILENO);
        close(pipe_fd[0]);
        close(pipe_fd[1]);
        execlp("ls", "ls", "-lR", NULL);
        perror("ls");
        _exit(1);
    }

    close(pipe_fd[1]);
    waitpid(child, NULL, 0);            /* bug: child may need a reader */
    while ((count = read(pipe_fd[0], buffer, sizeof(buffer))) > 0)
        write(STDOUT_FILENO, buffer, count);
    close(pipe_fd[0]);
    return 0;
}

If the recursive listing exceeds the pipe's finite capacity, the child blocks inside write and never exits, while the parent blocks in waitpid and never reaches read. The repair is to drain the pipe before waiting:

close(pipe_fd[1]);
while ((count = read(pipe_fd[0], buffer, sizeof(buffer))) > 0)
    write(STDOUT_FILENO, buffer, count);
waitpid(child, NULL, 0);

Common prevention strategies:

Strategy Rule Tradeoff
Resource hierarchy Acquire all locks in one global order Dynamic resource discovery can require releasing and retrying
Acquisition gate Hold one extra mutex while acquiring a complete resource set Can serialize acquisition and reduce concurrency
Admission limit Allow fewer contenders than the resource cycle can contain Simple, but may waste usable parallelism
State coordinator Record states and grant only safe combinations More bookkeeping; fairness must still be designed
Message-passing protocol Transfer resource ownership explicitly Avoids shared lock state but requires a correct protocol

An admission semaphore is one simple repair. With five philosophers, initializing it to four prevents all five from holding one fork at the same time:

sem_init(&room, 0, num_philosophers - 1);

sem_wait(&room);
pthread_mutex_lock(&forks[i]);
pthread_mutex_lock(&forks[(i + 1) % num_philosophers]);

eat(i);

pthread_mutex_unlock(&forks[(i + 1) % num_philosophers]);
pthread_mutex_unlock(&forks[i]);
sem_post(&room);

This breaks the circular-wait condition, although semaphore and mutex fairness still determines whether every philosopher eventually eats.

Releasing one fork after a timeout does not automatically solve the problem. If every philosopher retries in the same rhythm, they can all remain active yet make no progress. That is livelock. Randomized backoff can break the symmetry, but it does not replace a deliberate fairness policy.

Starvation is different from both: the system as a whole makes progress, but one participant waits indefinitely because others repeatedly win access. A deadlock stops a cycle of participants; starvation can affect just one.

Detailed notes - 7.2.2: Dining Philosophers and Deadlocks

1

deadlock: participants wait for resources held by one another

  • none can reach the operation that would release what another needs

2

English technical term: deadlock

  • "dead end" does not name this concurrency condition

3

five philosophers share five forks around a table

  • each alternates thinking and eating
  • eating requires both adjacent forks
  • naive protocol: acquire left fork, then wait for right without releasing left

4

if all five acquire their left fork, nobody can acquire the right fork

  • each needed fork is held by a neighbor who is also waiting
  • nobody can start eating and then release resources

5

two processes and two mutexes suffice for deadlock

  • first locks m1, then m2
  • second locks m2, then m1
  • if each acquires its first mutex, both wait forever for the second

6

deadlock also occurs without explicit mutexes

  • example: child executes ls with stdout redirected to a pipe
  • parent closes its write end, waits for child, then intends to read the pipe
  • may work for small output and hang for large output

7

child must finish writing ls output before it exits

  • parent waits for exit before starting to read
  • therefore nobody drains the pipe while the child is running

8

pipe buffer has finite capacity

  • once full, child's write blocks until a reader frees space
  • parent cannot read because it is blocked in wait

9

dependency cycle: parent waits for exit; child waits for parent's read

  • fix this example by reading / draining the pipe before waiting for child exit
  • correctness must not depend on a particular pipe-buffer size

10

naive philosopher implementation uses five fork mutexes

  • left(n) = (n - 1 + 5) % 5; right(n) = (n + 1) % 5
  • philosopher n locks forks[n], then forks[right(n)]
  • eat, release both, repeat
  • simultaneous first acquisitions reproduce the circular wait

11

limit the number attempting acquisition with a counting semaphore

  • down(sem) before taking forks; up(sem) after releasing both
  • initial count below 5 prevents all five holding one fork
  • count 1 serializes all eating
  • count 2 can admit neighbors that still interfere, leaving other possible work idle

12

at most four philosophers may compete under this semaphore solution

  • count 4 avoids the circular deadlock but can still leave only one eating
  • removing deadlock does not automatically maximize concurrency

13

resource ordering: always acquire lower-numbered fork before higher-numbered fork

  • philosopher between forks 4 and 0 takes 0 first, reversing the usual order
  • a consistent ordering prevents a circular acquisition dependency

14

ordering can be partial rather than a complete numbering

  • objects acquired together must be comparable under the ordering
  • can suit a dynamically changing resource set

15

resource ordering has practical tradeoffs

  • philosophers holding one fork may still leave usable resources idle
  • real programs may discover the next needed object only after locking others
  • if that object comes earlier in the order, held locks must be released and retried
  • repeated release / reacquisition can cost substantial work

16

steward mutex serializes acquisition of fork pairs

  • lock(steward); acquire both forks; unlock(steward); eat; release forks
  • eating and releasing forks do not need the steward
  • prevents circular acquisition deadlock
  • if current acquirer waits for a neighbor's fork, everyone else waits for steward, even philosophers who could otherwise eat

17

starvation: participant repeatedly fails to obtain the resources it needs

  • identical timeouts can make everyone release, wait, and retry in step
  • this active but unproductive cycle is livelock
  • random retry delays can break synchronized collisions
  • timeouts alone do not guarantee progress or fairness

18

state-based solution: thinking, hungry, or eating for each philosopher

  • one private binary semaphore can_eat[i], initially 0
  • hungry philosopher may eat when neither neighbor is eating / reserved to eat
  • otherwise waits until a neighbor releases forks and grants permission

19

one state_mutex protects the state array; separate fork mutexes are unnecessary

  • take_forks(i): lock; state[i] = hungry; test(i); unlock; down(can_eat[i])
  • put_forks(i): lock; state[i] = thinking; test(left); test(right); unlock
  • test(i): if i is hungry and neither neighbor is eating, set state[i] = eating and up(can_eat[i])
  • reserving the eating state before notification prevents conflicting grants
  • semaphore wait occurs outside state_mutex

20

state-based solution prevents deadlock but does not guarantee no starvation

  • neighbors 1 and 3 can alternate so that at least one is always eating
  • philosopher 2 then never sees both neighbors available

21

Chandy-Misra solution uses ownership transfer and messages

  • each fork is always held by one adjacent philosopher
  • fork is clean or dirty; eating makes it dirty
  • sent fork is cleaned before transfer
  • initially forks are dirty
  • complete algorithm also requires a suitable acyclic initial ownership ordering; the book's informal description omits this condition

22

hungry philosopher requests each missing fork from its holder

  • waits until both have arrived
  • if already holding both, can begin eating

23

on receiving a fork request:

  • dirty fork may be cleaned and sent when holder is not eating
  • hungry sender also requests it back
  • clean fork is retained; request is remembered
  • after eating, satisfy remembered requests by cleaning and sending dirty forks
  • never hand away a fork while actively using it to eat

24

clean/dirty distinction prevents neighbors endlessly reclaiming a newly received fork

  • clean fork can be retained until its holder gets a turn to eat
  • with the full protocol and progress assumptions, waiting does not become starvation

25

book explains why five philosophers make a useful teaching example

  • smaller cases admit special simplifications

26

one philosopher: no competition

  • two philosophers: only one can eat anyway
  • protect the pair of forks as one resource instead of independently locking both

27

three philosophers: again only one can eat at a time

  • one mutex around the meal captures all useful exclusion

28

four philosophers can eat as two fixed pairs of opposite seats

  • members of one pair do not share forks
  • synchronize between the two pairs rather than treat every fork independently

29

five participants remove these particular one-resource / fixed-pair simplifications

  • larger rings retain the same main acquisition and fairness problems
Parent waits for child termination while the child is blocked writing to a full pipe that only the parent can drain.
A full pipe can turn wait-before-read into deadlock. Open full size - Editable SVG
Opposing resource orders form a deadlock cycle; requiring lower then higher removes that possibility.
A global lock order breaks circular wait. Open full size - Editable SVG
Tests & experiments (42 files) - 7.2.2: Dining Philosophers and Deadlocks
Section test02 (07-02)In catalog
deadlock.cC / 27 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main()
{
    char buf[100];
    int pid, rc, fd[2];

    pipe(fd);
    pid = fork();
    if (pid == 0) {
        dup2(fd[1], 1);
        close(fd[1]);
        close(fd[0]);
        execlp("ls", "ls", "-lR", NULL);
        perror("ls");
        exit(1);
    }
    close(fd[1]);
    wait(NULL);
    while ((rc = read(fd[0], buf, sizeof(buf))) > 0)
        write(1, buf, rc);

    return 0;
}
philosophers-02.cC / 87 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum {
    num_philosophers = 5
};

typedef struct {
    pthread_mutex_t forks[num_philosophers];
    sem_t s;
} data_t;

typedef struct {
    data_t *data;
    int i;
} philosopher_data_t;

int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static void *philosopher(void *data)
{
    philosopher_data_t *p = data;
    data_t *d = p->data;
    int i = p->i;

    while (1) {
        think(i);
        sem_wait(&d->s);
        pthread_mutex_lock(&d->forks[i]);
        sleep(1);
        pthread_mutex_lock(&d->forks[right(i)]);
        eat(i);
        pthread_mutex_unlock(&d->forks[i]);
        pthread_mutex_unlock(&d->forks[right(i)]);
        sem_post(&d->s);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i, n;
    pthread_t t[num_philosophers];
    philosopher_data_t p[num_philosophers];
    data_t d;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <number of semaphores>\n", argv[0]);
        return 1;
    }
    n = atoi(argv[1]);

    sem_init(&d.s, 0, n);
    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_init(&d.forks[i], NULL);

    for (i = 0; i < num_philosophers; i++) {
        p[i].i = i;
        p[i].data = &d;
        pthread_create(&t[i], NULL, philosopher, &p[i]);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_destroy(&d.forks[i]);

    sem_destroy(&d.s);

    return 0;
}
philosophers-03.cC / 85 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

enum {
    num_philosophers = 5
};

typedef struct {
    pthread_mutex_t forks[num_philosophers];
} data_t;

typedef struct {
    data_t *data;
    int i;
} philosopher_data_t;

int right_fork(int i) { return (i + 1) % num_philosophers; }

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

void swap_int(int *x, int *y)
{
    int tmp;

    tmp = *x;
    *x = *y;
    *y = tmp;
}

static void *philosopher(void *data)
{
    philosopher_data_t *p = data;
    data_t *d = p->data;
    int i = p->i;
    int left = i, right = right_fork(i);
    if (right < left)
        swap_int(&left, &right);

    while (1) {
        think(i);
        sleep(2);
        pthread_mutex_lock(&d->forks[left]);
        pthread_mutex_lock(&d->forks[right]);
        eat(i);
        pthread_mutex_unlock(&d->forks[left]);
        pthread_mutex_unlock(&d->forks[right]);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i;
    pthread_t t[num_philosophers];
    philosopher_data_t p[num_philosophers];
    data_t d;

    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_init(&d.forks[i], NULL);

    for (i = 0; i < num_philosophers; i++) {
        p[i].i = i;
        p[i].data = &d;
        pthread_create(&t[i], NULL, philosopher, &p[i]);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_destroy(&d.forks[i]);

    return 0;
}
philosophers-04.cC / 79 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

enum {
    num_philosophers = 5
};

typedef struct {
    pthread_mutex_t forks[num_philosophers];
    pthread_mutex_t steward;
} data_t;

typedef struct {
    data_t *data;
    int i;
} philosopher_data_t;

int right_fork(int i) { return (i + 1) % num_philosophers; }

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static void *philosopher(void *data)
{
    philosopher_data_t *p = data;
    data_t *d = p->data;
    int i = p->i;
    int left = i, right = right_fork(i);

    while (1) {
        think(i);
        sleep(2);
        pthread_mutex_lock(&d->steward);
        pthread_mutex_lock(&d->forks[left]);
        pthread_mutex_lock(&d->forks[right]);
        pthread_mutex_unlock(&d->steward);
        eat(i);
        pthread_mutex_unlock(&d->forks[left]);
        pthread_mutex_unlock(&d->forks[right]);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i;
    pthread_t t[num_philosophers];
    philosopher_data_t p[num_philosophers];
    data_t d;

    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_init(&d.forks[i], NULL);
    pthread_mutex_init(&d.steward, NULL);

    for (i = 0; i < num_philosophers; i++) {
        p[i].i = i;
        p[i].data = &d;
        pthread_create(&t[i], NULL, philosopher, &p[i]);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_destroy(&d.forks[i]);
    pthread_mutex_destroy(&d.steward);

    return 0;
}
philosophers-05.cC / 86 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum {
    num_philosophers = 5
};

typedef struct {
    pthread_mutex_t forks[num_philosophers];
} data_t;

typedef struct {
    data_t *data;
    int i;
    unsigned int randseed;
} philosopher_data_t;

int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static void *philosopher(void *data)
{
    philosopher_data_t *p = data;
    data_t *d = p->data;
    int i = p->i;
    struct timespec ts;

    clock_gettime(CLOCK_REALTIME, &ts);
    ts.tv_sec += 5;

    while (1) {
        think(i);
        pthread_mutex_lock(&d->forks[i]);
        pthread_mutex_lock(&d->forks[right(i)]);
        eat(i);
        pthread_mutex_unlock(&d->forks[i]);
        pthread_mutex_unlock(&d->forks[right(i)]);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i, n;
    pthread_t t[num_philosophers];
    philosopher_data_t p[num_philosophers];
    data_t d;

    srand(time(NULL));
    if (argc < 2) {
        fprintf(stderr, "Usage: %s <number of semaphores>\n", argv[0]);
        return 1;
    }
    n = atoi(argv[1]);

    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_init(&d.forks[i], NULL);

    for (i = 0; i < num_philosophers; i++) {
        p[i].i = i;
        p[i].data = &d;
        pthread_create(&t[i], NULL, philosopher, &p[i]);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_destroy(&d.forks[i]);

    return 0;
}
philosophers-06.cC / 120 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum {
    num_philosophers = 5
};

enum possible_states {
    hungry,
    eating,
    thinking
};

typedef struct {
    int state[num_philosophers];
    sem_t can_eat[num_philosophers];
    pthread_mutex_t state_mut;
} data_t;

typedef struct {
    data_t *data;
    int i;
} philosopher_data_t;

static int left(int i)
{
    return (i - 1 + num_philosophers) % num_philosophers;
}

int right(int i)
{
    return (i + 1) % num_philosophers;
}

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static void test(data_t *d, int i)
{
    if (d->state[i] == hungry &&
            d->state[left(i)] != eating &&
            d->state[right(i)] != eating) {
        d->state[i] = eating;
        sem_post(&d->can_eat[i]);
    }
}

static void put_forks(data_t *d, int i)
{
    pthread_mutex_lock(&d->state_mut);
    d->state[i] = thinking;
    test(d, left(i));
    test(d, right(i));
    pthread_mutex_unlock(&d->state_mut);
}

static void take_forks(data_t *d, int i)
{
    pthread_mutex_lock(&d->state_mut);
    d->state[i] = hungry;
    test(d, i);
    pthread_mutex_unlock(&d->state_mut);
    sem_wait(&d->can_eat[i]);
}

static void *philosopher(void *data)
{
    philosopher_data_t *p = data;
    data_t *d = p->data;
    int i = p->i;

    while (1) {
        think(i);
        sleep(2);
        take_forks(d, i);
        eat(i);
        put_forks(d, i);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i;
    pthread_t t[num_philosophers];
    philosopher_data_t p[num_philosophers];
    data_t d;

    for (i = 0; i < num_philosophers; i++) {
        d.state[i] = thinking;
        sem_init(&d.can_eat[i], 0, 0);
    }
    pthread_mutex_init(&d.state_mut, NULL);

    for (i = 0; i < num_philosophers; i++) {
        p[i].i = i;
        p[i].data = &d;
        pthread_create(&t[i], NULL, philosopher, &p[i]);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    for (i = 0; i < num_philosophers; i++)
        sem_destroy(&d.can_eat[i]);
    pthread_mutex_destroy(&d.state_mut);

    return 0;
}
philosophers-07.cC / 71 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum { num_philosophers = 5 };

typedef struct {
    pthread_mutex_t forks[num_philosophers];
    sem_t data_sem;
    int i;
} data_t;

int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static void *philosopher(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        think(i);
        pthread_mutex_lock(&d->forks[i]);
        sleep(1);
        pthread_mutex_lock(&d->forks[right(i)]);
        eat(i);
        pthread_mutex_unlock(&d->forks[i]);
        pthread_mutex_unlock(&d->forks[right(i)]);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i;
    pthread_t t[num_philosophers];
    data_t d;

    sem_init(&d.data_sem, 0, 0);
    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_init(&d.forks[i], NULL);

    for (i = 0; i < num_philosophers; i++) {
        d.i = i;
        pthread_create(&t[i], NULL, philosopher, &d);
        sem_wait(&d.data_sem);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_destroy(&d.forks[i]);
    sem_destroy(&d.data_sem);

    return 0;
}
philosophers-08.cC / 82 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum { num_philosophers = 5 };

typedef struct {
    pthread_mutex_t forks[num_philosophers];
    sem_t data_sem;
    sem_t s;
    int i;
} data_t;

int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static void *philosopher(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        think(i);
        sem_wait(&d->s);
        pthread_mutex_lock(&d->forks[i]);
        sleep(1);
        pthread_mutex_lock(&d->forks[right(i)]);
        eat(i);
        pthread_mutex_unlock(&d->forks[i]);
        pthread_mutex_unlock(&d->forks[right(i)]);
        sem_post(&d->s);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i, n;
    pthread_t t[num_philosophers];
    data_t d;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <number of semaphores>\n", argv[0]);
        return 1;
    }
    n = atoi(argv[1]);

    sem_init(&d.data_sem, 0, 0);
    sem_init(&d.s, 0, n);
    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_init(&d.forks[i], NULL);

    for (i = 0; i < num_philosophers; i++) {
        d.i = i;
        pthread_create(&t[i], NULL, philosopher, &d);
        sem_wait(&d.data_sem);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_destroy(&d.forks[i]);
    sem_destroy(&d.s);
    sem_destroy(&d.data_sem);

    return 0;
}
philosophers-09.cC / 83 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum { num_philosophers = 5 };

typedef struct {
    pthread_mutex_t forks[num_philosophers];
    sem_t data_sem;
    int i;
} data_t;

int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

void swap_int(int *x, int *y)
{
    int tmp;

    tmp = *x;
    *x = *y;
    *y = tmp;
}

static void *philosopher(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);
    int l = i, r = right(i);
    if (r < l)
        swap_int(&l, &r);

    while (1) {
        think(i);
        sleep(2);
        pthread_mutex_lock(&d->forks[l]);
        pthread_mutex_lock(&d->forks[r]);
        eat(i);
        pthread_mutex_unlock(&d->forks[l]);
        pthread_mutex_unlock(&d->forks[r]);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i;
    pthread_t t[num_philosophers];
    data_t d;

    sem_init(&d.data_sem, 0, 0);
    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_init(&d.forks[i], NULL);

    for (i = 0; i < num_philosophers; i++) {
        d.i = i;
        pthread_create(&t[i], NULL, philosopher, &d);
        sem_wait(&d.data_sem);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_destroy(&d.forks[i]);
    sem_destroy(&d.data_sem);

    return 0;
}
philosophers-10.cC / 77 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum { num_philosophers = 5 };

typedef struct {
    sem_t data_sem;
    pthread_mutex_t forks[num_philosophers];
    int i;
    pthread_mutex_t steward;
} data_t;

int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static void *philosopher(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);
    int l = i, r = right(i);

    while (1) {
        think(i);
        sleep(2);
        pthread_mutex_lock(&d->steward);
        pthread_mutex_lock(&d->forks[l]);
        pthread_mutex_lock(&d->forks[r]);
        pthread_mutex_unlock(&d->steward);
        eat(i);
        pthread_mutex_unlock(&d->forks[l]);
        pthread_mutex_unlock(&d->forks[r]);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i;
    pthread_t t[num_philosophers];
    data_t d;

    sem_init(&d.data_sem, 0, 0);
    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_init(&d.forks[i], NULL);
    pthread_mutex_init(&d.steward, NULL);

    for (i = 0; i < num_philosophers; i++) {
        d.i = i;
        pthread_create(&t[i], NULL, philosopher, &d);
        sem_wait(&d.data_sem);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    sem_destroy(&d.data_sem);
    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_destroy(&d.forks[i]);
    pthread_mutex_destroy(&d.steward);

    return 0;
}
philosophers-11.cC / 89 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum {
    num_philosophers = 5,
    max_time = 5
};

typedef struct {
    sem_t data_sem;
    pthread_mutex_t forks[num_philosophers];
    int i;
    unsigned int randseed;
} data_t;

int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static void *philosopher(void *data)
{
    data_t *d = data;
    int i = d->i;
    unsigned int randseed = d->randseed;
    sem_post(&d->data_sem);
    int l = i, r = right(i);
    struct timespec current_time, timeout_left, timeout_right;
    int time_left, time_right;

    clock_gettime(CLOCK_REALTIME, &current_time);
    time_left = rand_r(&randseed) % max_time;
    time_right = rand_r(&randseed) % max_time;
    timeout_left = current_time;
    timeout_left.tv_sec += time_left;
    timeout_right = current_time;
    timeout_right.tv_sec += time_right;

    while (1) {
        think(i);
        pthread_mutex_timedlock(&d->forks[l], &timeout_left);
        sleep(2);
        pthread_mutex_timedlock(&d->forks[r], &timeout_right);
        eat(i);
        pthread_mutex_unlock(&d->forks[l]);
        pthread_mutex_unlock(&d->forks[r]);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i;
    pthread_t t[num_philosophers];
    data_t d;

    d.randseed = time(NULL);
    sem_init(&d.data_sem, 0, 0);
    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_init(&d.forks[i], NULL);

    for (i = 0; i < num_philosophers; i++) {
        d.i = i;
        d.randseed++;
        pthread_create(&t[i], NULL, philosopher, &d);
        sem_wait(&d.data_sem);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    sem_destroy(&d.data_sem);
    for (i = 0; i < num_philosophers; i++)
        pthread_mutex_destroy(&d.forks[i]);

    return 0;
}
philosophers-12.cC / 119 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum {
    num_philosophers = 5
};

enum possible_states {
    hungry,
    eating,
    thinking
};

typedef struct {
    sem_t data_sem;
    int state[num_philosophers];
    sem_t can_eat[num_philosophers];
    pthread_mutex_t state_mut;
    int i;
} data_t;


static int left(int i)
{
    return (i - 1 + num_philosophers) % num_philosophers;
}

int right(int i)
{
    return (i + 1) % num_philosophers;
}

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static void test(data_t *d, int i)
{
    if (d->state[i] == hungry &&
            d->state[left(i)] != eating &&
            d->state[right(i)] != eating) {
        d->state[i] = eating;
        sem_post(&d->can_eat[i]);
    }
}

static void put_forks(data_t *d, int i)
{
    pthread_mutex_lock(&d->state_mut);
    d->state[i] = thinking;
    test(d, left(i));
    test(d, right(i));
    pthread_mutex_unlock(&d->state_mut);
}

static void take_forks(data_t *d, int i)
{
    pthread_mutex_lock(&d->state_mut);
    d->state[i] = hungry;
    test(d, i);
    pthread_mutex_unlock(&d->state_mut);
    sem_wait(&d->can_eat[i]);
}

static void *philosopher(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        think(i);
        sleep(2);
        take_forks(d, i);
        eat(i);
        put_forks(d, i);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i;
    pthread_t t[num_philosophers];
    data_t d;

    sem_init(&d.data_sem, 0, 0);
    for (i = 0; i < num_philosophers; i++) {
        d.state[i] = thinking;
        sem_init(&d.can_eat[i], 0, 0);
    }
    pthread_mutex_init(&d.state_mut, NULL);

    for (i = 0; i < num_philosophers; i++) {
        d.i = i;
        pthread_create(&t[i], NULL, philosopher, &d);
        sem_wait(&d.data_sem);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    sem_destroy(&d.data_sem);
    for (i = 0; i < num_philosophers; i++)
        sem_destroy(&d.can_eat[i]);
    pthread_mutex_destroy(&d.state_mut);

    return 0;
}
philosophers-13.cC / 160 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum {
    num_philosophers = 5,
    num_hands = 2
};

enum hands {
    left_hand,
    right_hand
};

enum fork_states {
    dirty,
    clean
};

typedef struct {
    sem_t data_sem;
    int has_fork[num_philosophers][num_hands];
    int wants_fork[num_philosophers][num_hands];
    sem_t forks[num_philosophers];
    int fork_state[num_philosophers];
    pthread_mutex_t state_mut;
    int i;
} data_t;

static void data_init(data_t *d)
{
    int i;

    sem_init(&d->data_sem, 0, 0);
    for (i = 0; i < num_philosophers; i++) {
        d->has_fork[i][left_hand] = 1;
        d->has_fork[i][right_hand] = 0;
        d->wants_fork[i][left_hand] = 0;
        d->wants_fork[i][right_hand] = 0;
        sem_init(&d->forks[i], 0, 1);
        d->fork_state[i] = dirty;
    }
    pthread_mutex_init(&d->state_mut, NULL);
}

static void data_destroy(data_t *d)
{
    int i;

    sem_destroy(&d->data_sem);
    for (i = 0; i < num_philosophers; i++)
        sem_destroy(&d->forks[i]);
    pthread_mutex_destroy(&d->state_mut);
}

static int left_of(int i)
{
    return (i - 1 + num_philosophers) % num_philosophers;
}

static int right_of(int i)
{
    return (i + 1) % num_philosophers;
}

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static void *philosopher(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        think(i);
        sleep(1);

        if (d->has_fork[i][left_hand] &&
                d->wants_fork[left_of(i)][right_hand] &&
                d->fork_state[i] == dirty) {
            d->fork_state[i] = clean;
            d->wants_fork[i][left_hand] = 1;
            d->has_fork[i][left_hand] = 0;
            d->has_fork[left_of(i)][right_hand] = 1;
            sem_post(&d->forks[i]);
        }

        if (!d->has_fork[i][left_hand]) {
            d->wants_fork[i][left_hand] = 1;
            sem_wait(&d->forks[i]);
        }

        if (d->has_fork[i][right_hand] &&
                d->wants_fork[right_of(i)][left_hand] &&
                d->fork_state[right_of(i)] == dirty) {
            d->fork_state[right_of(i)] = clean;
            d->wants_fork[i][right_hand] = 1;
            d->has_fork[i][right_hand] = 0;
            d->has_fork[right_of(i)][left_hand] = 1;
            sem_post(&d->forks[right_of(i)]);
        }

        if (!d->has_fork[i][right_hand]) {
            d->wants_fork[i][right_hand] = 1;
            sem_wait(&d->forks[right_of(i)]);
        }

        eat(i);
        d->fork_state[i] = dirty;
        d->fork_state[right_of(i)] = dirty;

        /* TODO: merge with the previous one */
        if (d->wants_fork[left_of(i)][right_hand]) {
            d->fork_state[i] = clean;
            d->has_fork[i][left_hand] = 0;
            d->has_fork[left_of(i)][right_hand] = 1;
            sem_post(&d->forks[left_of(i)]);
        }
        if (d->wants_fork[right_of(i)][left_hand]) {
            d->fork_state[right_of(i)] = clean;
            d->has_fork[i][right_hand] = 0;
            d->has_fork[right_of(i)][left_hand] = 1;
            sem_post(&d->forks[right_of(i)]);
        }
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i;
    pthread_t t[num_philosophers];
    data_t d;

    data_init(&d);

    for (i = 0; i < num_philosophers; i++) {
        d.i = i;
        pthread_create(&t[i], NULL, philosopher, &d);
        sem_wait(&d.data_sem);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    data_destroy(&d);

    return 0;
}
philosophers-14.cC / 154 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum {
    num_philosophers = 5,
    num_hands = 2
};

enum hands {
    left_hand,
    right_hand
};

enum fork_states {
    dirty,
    clean
};

typedef struct {
    sem_t data_sem;
    int has_fork[num_philosophers][num_hands];
    int wants_fork[num_philosophers][num_hands];
    sem_t forks[num_philosophers];
    int fork_state[num_philosophers];
    pthread_mutex_t state_mut;
    int i;
} data_t;

static void data_init(data_t *d)
{
    int i;

    sem_init(&d->data_sem, 0, 0);
    for (i = 0; i < num_philosophers; i++) {
        d->has_fork[i][left_hand] = 1;
        d->has_fork[i][right_hand] = 0;
        d->wants_fork[i][left_hand] = 0;
        d->wants_fork[i][right_hand] = 0;
        sem_init(&d->forks[i], 0, 1);
        d->fork_state[i] = dirty;
    }
    pthread_mutex_init(&d->state_mut, NULL);
}

static void data_destroy(data_t *d)
{
    int i;

    sem_destroy(&d->data_sem);
    for (i = 0; i < num_philosophers; i++)
        sem_destroy(&d->forks[i]);
    pthread_mutex_destroy(&d->state_mut);
}

static int left_of(int i)
{
    return (i - 1 + num_philosophers) % num_philosophers;
}

static int right_of(int i)
{
    return (i + 1) % num_philosophers;
}

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static void give_fork(data_t *d, int i, int shift_i, int sem_i, int hand,
                      int include_wants)
{
    int other_hand = (hand + 1) % num_hands;

    if (d->wants_fork[shift_i][other_hand] &&
            (!include_wants || d->has_fork[i][hand] &&
             d->fork_state[sem_i] == dirty)) {
        pthread_mutex_lock(&d->state_mut);
        d->fork_state[sem_i] = clean;
        if (include_wants)
            d->wants_fork[i][hand] = 1;
        d->has_fork[i][hand] = 0;
        d->has_fork[shift_i][other_hand] = 1;
        pthread_mutex_unlock(&d->state_mut);
        sem_post(&d->forks[sem_i]);
    }
}

static void *philosopher(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        think(i);
        sleep(1);

        give_fork(d, i, left_of(i), i, left_hand, 1);
        if (!d->has_fork[i][left_hand]) {
            pthread_mutex_lock(&d->state_mut);
            d->wants_fork[i][left_hand] = 1;
            pthread_mutex_unlock(&d->state_mut);
            sem_wait(&d->forks[i]);
        }

        give_fork(d, i, right_of(i), right_of(i), right_hand, 1);
        if (!d->has_fork[i][right_hand]) {
            pthread_mutex_lock(&d->state_mut);
            d->wants_fork[i][right_hand] = 1;
            pthread_mutex_unlock(&d->state_mut);
            sem_wait(&d->forks[right_of(i)]);
        }

        eat(i);
        d->fork_state[i] = dirty;
        d->fork_state[right_of(i)] = dirty;

        give_fork(d, i, left_of(i), i, left_hand, 0);
        give_fork(d, i, right_of(i), right_of(i), right_hand, 0);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i;
    pthread_t t[num_philosophers];
    data_t d;

    data_init(&d);

    for (i = 0; i < num_philosophers; i++) {
        d.i = i;
        pthread_create(&t[i], NULL, philosopher, &d);
        sem_wait(&d.data_sem);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    data_destroy(&d);

    return 0;
}
philosophers-15.cC / 277 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum {
    num_philosophers = 5,
    num_hands = 2
};

enum hands {
    left_hand,
    right_hand
};

enum fork_states {
    dirty,
    clean
};

typedef struct {
    sem_t data_sem;
    int has_fork[num_philosophers][num_hands];
    int wants_fork[num_philosophers][num_hands];
    sem_t events[num_philosophers];
    int fork_state[num_philosophers];
    pthread_mutex_t state_mut;
    int i;
} data_t;

static int left_of(int i)
{
    return (i - 1 + num_philosophers) % num_philosophers;
}

static int right_of(int i)
{
    return (i + 1) % num_philosophers;
}

static int fork_of(int i, int hand)
{
    return (hand == left_hand) ? i : right_of(i);
}

static int neighbor_of(int i, int hand)
{
    return (hand == left_hand) ? left_of(i) : right_of(i);
}

static int neighbor_hand(int hand)
{
    return (hand == left_hand) ? right_hand : left_hand;
}

static void data_init(data_t *d)
{
    int i, a, b;

    sem_init(&d->data_sem, 0, 0);

    for (i = 0; i < num_philosophers; i++) {

        d->has_fork[i][left_hand] = 0;
        d->has_fork[i][right_hand] = 0;

        d->wants_fork[i][left_hand] = 0;
        d->wants_fork[i][right_hand] = 0;

        sem_init(&d->events[i], 0, 0);
        d->fork_state[i] = dirty;
    }

    pthread_mutex_init(&d->state_mut, NULL);

    for (i = 0; i < num_philosophers; i++) {
        a = i;
        b = left_of(i);

        if (a < b)
            d->has_fork[a][left_hand] = 1;
        else
            d->has_fork[b][right_hand] = 1;
    }
}

static void data_destroy(data_t *d)
{
    int i;

    sem_destroy(&d->data_sem);

    for (i = 0; i < num_philosophers; i++)
        sem_destroy(&d->events[i]);

    pthread_mutex_destroy(&d->state_mut);
}

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static void give_fork(data_t *d, int i, int hand, int hungry)
{
    int neighbor, other_hand, fork, gave;

    neighbor = neighbor_of(i, hand);
    other_hand = neighbor_hand(hand);
    fork = fork_of(i, hand);
    gave = 0;

    pthread_mutex_lock(&d->state_mut);

    if (d->has_fork[i][hand] &&
            d->wants_fork[neighbor][other_hand] &&
            d->fork_state[fork] == dirty) {

        d->fork_state[fork] = clean;
        d->wants_fork[neighbor][other_hand] = 0;

        d->has_fork[i][hand] = 0;
        d->has_fork[neighbor][other_hand] = 1;

        if (hungry)
            d->wants_fork[i][hand] = 1;

        gave = 1;
    }

    pthread_mutex_unlock(&d->state_mut);

    if (gave)
        sem_post(&d->events[neighbor]);
}

static void give_forks(data_t *d, int i, int hungry)
{
    give_fork(d, i, left_hand, hungry);
    give_fork(d, i, right_hand, hungry);
}

static void request_fork(data_t *d, int i, int hand)
{
    int neighbor, notify;

    neighbor = neighbor_of(i, hand);
    notify = 0;

    pthread_mutex_lock(&d->state_mut);

    if (!d->has_fork[i][hand] && !d->wants_fork[i][hand]) {
        d->wants_fork[i][hand] = 1;
        notify = 1;
    }

    pthread_mutex_unlock(&d->state_mut);

    if (notify)
        sem_post(&d->events[neighbor]);
}

static void request_forks(data_t *d, int i)
{
    request_fork(d, i, left_hand);
    request_fork(d, i, right_hand);
}

static int ready_to_eat(data_t *d, int i)
{
    int hand, result, neighbor, other_hand, fork;

    result = 1;

    pthread_mutex_lock(&d->state_mut);

    if (!d->has_fork[i][left_hand] || !d->has_fork[i][right_hand])
        result = 0;
    else
        for (hand = 0; hand < num_hands; hand++) {
            neighbor = neighbor_of(i, hand);
            other_hand = neighbor_hand(hand);
            fork = fork_of(i, hand);

            if (d->wants_fork[neighbor][other_hand] &&
                    d->fork_state[fork] == dirty) {
                result = 0;
                break;
            }
        }

    pthread_mutex_unlock(&d->state_mut);

    return result;
}

static void make_forks_dirty(data_t *d, int i)
{
    int left, right;

    left = fork_of(i, left_hand);
    right = fork_of(i, right_hand);

    pthread_mutex_lock(&d->state_mut);

    if (d->has_fork[i][left_hand])
        d->fork_state[left] = dirty;

    if (d->has_fork[i][right_hand])
        d->fork_state[right] = dirty;

    pthread_mutex_unlock(&d->state_mut);
}

static void *philosopher(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        think(i);
        sleep(1);

        while (1) {
            give_forks(d, i, 1);
            request_forks(d, i);

            if (ready_to_eat(d, i))
                break;

            sem_wait(&d->events[i]);
        }

        eat(i);
        sleep(1);

        make_forks_dirty(d, i);
        give_forks(d, i, 0);
    }

    return NULL;
}

int main()
{
    int i, failed;
    pthread_t t[num_philosophers];
    data_t d;

    data_init(&d);

    for (i = 0; i < num_philosophers; i++) {
        d.i = i;

        failed = pthread_create(&t[i], NULL, philosopher, &d);
        if (failed) {
            fprintf(stderr, "pthread_create failed\n");
            return 1;
        }

        sem_wait(&d.data_sem);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    data_destroy(&d);

    return 0;
}
philosophers-16-2-3.cC / 83 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum {
    num_philosophers = 3
};

typedef struct {
    sem_t data_sem;
    pthread_mutex_t forks;
    int i;
} data_t;

static void data_init(data_t *d)
{
    sem_init(&d->data_sem, 0, 0);
    pthread_mutex_init(&d->forks, NULL);
}

static void data_destroy(data_t *d)
{
    sem_destroy(&d->data_sem);
    pthread_mutex_destroy(&d->forks);
}

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static void *philosopher(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        think(i);
        sleep(1);

        pthread_mutex_lock(&d->forks);
        eat(i);
        pthread_mutex_unlock(&d->forks);
    }

    return NULL;
}

int main()
{
    int i, failed;
    pthread_t t[num_philosophers];
    data_t d;

    data_init(&d);

    for (i = 0; i < num_philosophers; i++) {
        d.i = i;

        failed = pthread_create(&t[i], NULL, philosopher, &d);
        if (failed) {
            fprintf(stderr, "pthread_create failed\n");
            return 1;
        }

        sem_wait(&d.data_sem);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    data_destroy(&d);

    return 0;
}
philosophers-17-4.cC / 129 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum {
    num_philosophers = 4
};

enum possible_states {
    thinking,
    hungry,
    eating
};

typedef struct {
    sem_t data_sem;
    int state[num_philosophers];
    pthread_mutex_t state_mut;
    sem_t events[num_philosophers];
    int i;
} data_t;

static void data_init(data_t *d)
{
    int i;

    sem_init(&d->data_sem, 0, 0);
    pthread_mutex_init(&d->state_mut, NULL);

    for (i = 0; i < num_philosophers; i++) {
        d->state[i] = thinking;
        sem_init(&d->events[i], 0, 0);
    }
}

static void data_destroy(data_t *d)
{
    int i;

    sem_destroy(&d->data_sem);
    pthread_mutex_destroy(&d->state_mut);
    for (i = 0; i < num_philosophers; i++)
        sem_destroy(&d->events[i]);
}

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static int left_of(int i)
{
    return (i - 1 + num_philosophers) % num_philosophers;
}

static int right_of(int i)
{
    return (i + 1) % num_philosophers;
}

static void *philosopher(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        pthread_mutex_lock(&d->state_mut);
        d->state[i] = thinking;
        pthread_mutex_unlock(&d->state_mut);
        think(i);
        sleep(1);

        pthread_mutex_lock(&d->state_mut);
        d->state[i] = hungry;
        if (d->state[left_of(i)] == eating)
            sem_wait(&d->events[i]);
        if (d->state[right_of(i)] == eating)
            sem_wait(&d->events[i]);
        if (d->state[left_of(i)] != eating &&
                d->state[right_of(i)] != eating) {
            d->state[i] = eating;
            eat(i);
            d->state[i] = thinking;
            if (d->state[left_of(i)] == hungry)
                sem_post(&d->events[left_of(i)]);
            if (d->state[right_of(i)] == hungry)
                sem_post(&d->events[right_of(i)]);
        }
        pthread_mutex_unlock(&d->state_mut);
    }

    return NULL;
}

int main()
{
    int i, failed;
    pthread_t t[num_philosophers];
    data_t d;

    data_init(&d);

    for (i = 0; i < num_philosophers; i++) {
        d.i = i;

        failed = pthread_create(&t[i], NULL, philosopher, &d);
        if (failed) {
            fprintf(stderr, "pthread_create failed\n");
            return 1;
        }

        sem_wait(&d.data_sem);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    data_destroy(&d);

    return 0;
}
philosophers-18-4.cC / 135 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum {
    num_philosophers = 4,
    think_seconds = 3,
    eat_seconds = 1
};

enum possible_states {
    thinking,
    hungry,
    eating
};

typedef struct {
    sem_t data_sem;
    int state[num_philosophers];
    pthread_mutex_t state_mut;
    sem_t events[num_philosophers];
    int i;
} data_t;

static void data_init(data_t *d)
{
    int i;

    sem_init(&d->data_sem, 0, 0);
    pthread_mutex_init(&d->state_mut, NULL);
    for (i = 0; i < num_philosophers; i++) {
        d->state[i] = thinking;
        sem_init(&d->events[i], 0, 0);
    }
}

static void data_destroy(data_t *d)
{
    int i;

    sem_destroy(&d->data_sem);
    pthread_mutex_destroy(&d->state_mut);
    for (i = 0; i < num_philosophers; i++)
        sem_destroy(&d->events[i]);
}

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
    sleep(think_seconds);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
    sleep(eat_seconds);
}

static int left_of(int i)
{
    return (i - 1 + num_philosophers) % num_philosophers;
}

static int right_of(int i)
{
    return (i + 1) % num_philosophers;
}

static void test(data_t *d, int i)
{
    if (d->state[i] == hungry &&
            d->state[left_of(i)] != eating &&
            d->state[right_of(i)] != eating) {
        d->state[i] = eating;
        sem_post(&d->events[i]);
    }
}

static void *philosopher(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        think(i);

        pthread_mutex_lock(&d->state_mut);
        d->state[i] = hungry;
        test(d, i);
        pthread_mutex_unlock(&d->state_mut);

        sem_wait(&d->events[i]);
        eat(i);

        pthread_mutex_lock(&d->state_mut);
        d->state[i] = thinking;
        test(d, left_of(i));
        test(d, right_of(i));
        pthread_mutex_unlock(&d->state_mut);

    }

    return NULL;
}

int main()
{
    int i, failed;
    pthread_t t[num_philosophers];
    data_t d;

    data_init(&d);

    for (i = 0; i < num_philosophers; i++) {
        d.i = i;

        failed = pthread_create(&t[i], NULL, philosopher, &d);
        if (failed) {
            fprintf(stderr, "pthread_create failed\n");
            return 1;
        }

        sem_wait(&d.data_sem);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    data_destroy(&d);

    return 0;
}
Section testphilosophers-00 (07-02-02)In catalog
MakefileMake / 28 lines
SRCMODULES = atomic.asm futex.c mutex.c semaphore.c
OBJMODULES = $(SRCMODULES:.asm=.o)
OBJMODULES := $(OBJMODULES:.c=.o)

PROGRAMS = main

CC = gcc
CFLAGS = -g -Wall -O0

ASM = nasm
AFLAGS = -g -f elf64

all: $(PROGRAMS)

%.o: %.asm %.h
    $(ASM) $(AFLAGS) $< -o $@

%.o: %.c %.h
    $(CC) $(CFLAGS) -c $< -o $@

$(PROGRAMS): %: %.c $(OBJMODULES)
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)

ctags:
    ctags *.c *.h
atomic.asmAssembly / 26 lines
global xchg
global cmpxchg
global dec
global inc

section .text

xchg:
    mov     eax, esi
    xchg        dword [rdi], eax
    ret

cmpxchg:
    mov     eax, esi
    lock cmpxchg    dword [rdi], edx
    ret

dec:
    mov     eax, -1
    lock xadd   dword [rdi], eax
    ret

inc:
    mov     eax, 1
    lock xadd   dword [rdi], eax
    ret
atomic.hC / 9 lines
#ifndef ATOMIC_H
#define ATOMIC_H

int xchg(int *var, int old);
int cmpxchg(int *var, int old, int new);
int dec(int *var);
int inc(int *var);

#endif
futex.cC / 15 lines
#include <linux/futex.h>
#include <sys/syscall.h>
#include <unistd.h>

#include "futex.h"

void futex_wait(int *futex, int expected)
{
    syscall(SYS_futex, futex, FUTEX_WAIT, expected, NULL, NULL, 0);
}

void futex_wake(int *futex, int num)
{
    syscall(SYS_futex, futex, FUTEX_WAKE, num, NULL, NULL, 0);
}
futex.hC / 7 lines
#ifndef FUTEX_H
#define FUTEX_H

void futex_wait(int *futex, int expected);
void futex_wake(int *futex, int num);

#endif
main.cC / 84 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "mutex.h"
#include "semaphore.h"

enum {
    num_philosophers = 5
};

typedef struct {
    int forks[num_philosophers];
    semaphore_t s;
} data_t;

typedef struct {
    data_t *data;
    int i;
} philosopher_data_t;

int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static void *philosopher(void *data)
{
    philosopher_data_t *p = data;
    data_t *d = p->data;
    int i = p->i;

    while (1) {
        think(i);
        down(&d->s);
        lock(&d->forks[i]);
        sleep(1);
        lock(&d->forks[right(i)]);
        eat(i);
        unlock(&d->forks[i]);
        unlock(&d->forks[right(i)]);
        up(&d->s);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i, n;
    pthread_t t[num_philosophers];
    philosopher_data_t p[num_philosophers];
    data_t d;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <number of semaphores>\n", argv[0]);
        return 1;
    }
    n = atoi(argv[1]);

    init(&d.s, n);
    for (i = 0; i < num_philosophers; i++)
        d.forks[i] = 0;

    for (i = 0; i < num_philosophers; i++) {
        p[i].i = i;
        p[i].data = &d;
        pthread_create(&t[i], NULL, philosopher, &p[i]);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    return 0;
}
mutex.cC / 30 lines
#include "atomic.h"
#include "futex.h"
#include "mutex.h"

void lock(int *m)
{
    int old;

    old = cmpxchg(m, 0, 1);
    if (old != 0) {
        if (old != 2)
            old = xchg(m, 2);
        while (old != 0) {
            futex_wait(m, 2);
            old = xchg(m, 2);
        }
    }
}

void unlock(int *m)
{
    int old;

    old = dec(m);
    if (old != 1) {
        *m = 0;
        futex_wake(m, 1);
    }
}

mutex.hC / 7 lines
#ifndef MUTEX_H
#define MUTEX_H

void lock(int *m);
void unlock(int *m);

#endif
semaphore.cC / 51 lines
#include "atomic.h"
#include "futex.h"
#include "semaphore.h"

void init(semaphore_t *s, int value)
{
    s->value = value;
    s->waiters = 0;
}

static int try_down(semaphore_t *s)
{
    int value, old;

    value = s->value;
    while (value > 0) {
        old = cmpxchg(&s->value, value, value - 1);
        if (old == value)
            return 1;
        value = old;
    }

    return 0;
}

void down(semaphore_t *s)
{
    int success;

    success = try_down(s);
    if (success)
        return;

    inc(&s->waiters);
    while (1) {
        success = try_down(s);
        if (success) {
            dec(&s->waiters);
            return;
        }
        futex_wait(&s->value, 0);
    }
}

void up(semaphore_t *s)
{
    inc(&s->value);
    if (s->waiters > 0)
        futex_wake(&s->value, 1);
}

semaphore.hC / 13 lines
#ifndef SEMAPHORE_H
#define SEMAPHORE_H

typedef struct {
    int value;
    int waiters;
} semaphore_t;

void init(semaphore_t *s, int value);
void down(semaphore_t *s);
void up(semaphore_t *s);

#endif
test_mutex.cC / 54 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "mutex.h"

enum {
    pause_seconds = 1
};

typedef struct {
    int val;
    int x;
} data_t;

static void *worker_thread(void *data)
{
    data_t *d = data;

    while (1) {
        lock(&d->val);
        d->x++;
        unlock(&d->val);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i, n;
    pthread_t t;
    data_t d;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
        return 1;
    }
    n = atoi(argv[1]);

    d.val = 0;
    d.x = 0;

    for (i = 0; i < n; i++)
        pthread_create(&t, NULL, worker_thread, &d);

    while (1) {
        printf("%d\n", d.x);
        sleep(pause_seconds);
    }

    return 0;
}
test_semaphore.cC / 56 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "semaphore.h"

enum {
    pause_seconds = 1
};

typedef struct {
    semaphore_t s;
    int x;
} data_t;

static void *worker_thread(void *data)
{
    data_t *d = data;

    while (1) {
        down(&d->s);
        d->x++;
        up(&d->s);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i, n;
    pthread_t t;
    data_t d;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
        return 1;
    }
    n = atoi(argv[1]);

    init(&d.s, 1);
    d.x = 0;

    for (i = 0; i < n; i++)
        pthread_create(&t, NULL, worker_thread, &d);

    while (1) {
        down(&d.s);
        printf("%d\n", d.x);
        up(&d.s);
        sleep(pause_seconds);
    }

    return 0;
}
Section testphilosophers-01 (07-02-02)In catalog
MakefileMake / 28 lines
SRCMODULES = atomic.asm futex.c mutex.c semaphore.c
OBJMODULES = $(SRCMODULES:.asm=.o)
OBJMODULES := $(OBJMODULES:.c=.o)

PROGRAMS = main

CC = gcc
CFLAGS = -g -Wall -O0

ASM = nasm
AFLAGS = -g -f elf64

all: $(PROGRAMS)

%.o: %.asm %.h
    $(ASM) $(AFLAGS) $< -o $@

%.o: %.c %.h
    $(CC) $(CFLAGS) -c $< -o $@

$(PROGRAMS): %: %.c $(OBJMODULES)
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)

ctags:
    ctags *.c *.h
atomic.asmAssembly / 26 lines
global xchg
global cmpxchg
global dec
global inc

section .text

xchg:
    mov     eax, esi
    xchg        dword [rdi], eax
    ret

cmpxchg:
    mov     eax, esi
    lock cmpxchg    dword [rdi], edx
    ret

dec:
    mov     eax, -1
    lock xadd   dword [rdi], eax
    ret

inc:
    mov     eax, 1
    lock xadd   dword [rdi], eax
    ret
atomic.hC / 9 lines
#ifndef ATOMIC_H
#define ATOMIC_H

int xchg(int *var, int old);
int cmpxchg(int *var, int old, int new);
int dec(int *var);
int inc(int *var);

#endif
futex.cC / 15 lines
#include <linux/futex.h>
#include <sys/syscall.h>
#include <unistd.h>

#include "futex.h"

void futex_wait(int *futex, int expected)
{
    syscall(SYS_futex, futex, FUTEX_WAIT, expected, NULL, NULL, 0);
}

void futex_wake(int *futex, int num)
{
    syscall(SYS_futex, futex, FUTEX_WAKE, num, NULL, NULL, 0);
}
futex.hC / 7 lines
#ifndef FUTEX_H
#define FUTEX_H

void futex_wait(int *futex, int expected);
void futex_wake(int *futex, int num);

#endif
main.cC / 85 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "mutex.h"
#include "semaphore.h"

enum {
    num_philosophers = 5
};

typedef struct {
    int forks[num_philosophers];
} data_t;

typedef struct {
    data_t *data;
    int i;
} philosopher_data_t;

int right_fork(int i) { return (i + 1) % num_philosophers; }

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

void swap_int(int *x, int *y)
{
    int tmp;

    tmp = *x;
    *x = *y;
    *y = tmp;
}

static void *philosopher(void *data)
{
    philosopher_data_t *p = data;
    data_t *d = p->data;
    int i = p->i;
    int left = i, right = right_fork(i);
    if (right < left)
        swap_int(&left, &right);

    while (1) {
        think(i);
        sleep(4);
        lock(&d->forks[left]);
        lock(&d->forks[right]);
        eat(i);
        unlock(&d->forks[left]);
        unlock(&d->forks[right]);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i;
    pthread_t t[num_philosophers];
    philosopher_data_t p[num_philosophers];
    data_t d;

    for (i = 0; i < num_philosophers; i++)
        d.forks[i] = 0;

    for (i = 0; i < num_philosophers; i++) {
        p[i].i = i;
        p[i].data = &d;
        pthread_create(&t[i], NULL, philosopher, &p[i]);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    return 0;
}
mutex.cC / 30 lines
#include "atomic.h"
#include "futex.h"
#include "mutex.h"

void lock(int *m)
{
    int old;

    old = cmpxchg(m, 0, 1);
    if (old != 0) {
        if (old != 2)
            old = xchg(m, 2);
        while (old != 0) {
            futex_wait(m, 2);
            old = xchg(m, 2);
        }
    }
}

void unlock(int *m)
{
    int old;

    old = dec(m);
    if (old != 1) {
        *m = 0;
        futex_wake(m, 1);
    }
}

mutex.hC / 7 lines
#ifndef MUTEX_H
#define MUTEX_H

void lock(int *m);
void unlock(int *m);

#endif
semaphore.cC / 51 lines
#include "atomic.h"
#include "futex.h"
#include "semaphore.h"

void init(semaphore_t *s, int value)
{
    s->value = value;
    s->waiters = 0;
}

static int try_down(semaphore_t *s)
{
    int value, old;

    value = s->value;
    while (value > 0) {
        old = cmpxchg(&s->value, value, value - 1);
        if (old == value)
            return 1;
        value = old;
    }

    return 0;
}

void down(semaphore_t *s)
{
    int success;

    success = try_down(s);
    if (success)
        return;

    inc(&s->waiters);
    while (1) {
        success = try_down(s);
        if (success) {
            dec(&s->waiters);
            return;
        }
        futex_wait(&s->value, 0);
    }
}

void up(semaphore_t *s)
{
    inc(&s->value);
    if (s->waiters > 0)
        futex_wake(&s->value, 1);
}

semaphore.hC / 13 lines
#ifndef SEMAPHORE_H
#define SEMAPHORE_H

typedef struct {
    int value;
    int waiters;
} semaphore_t;

void init(semaphore_t *s, int value);
void down(semaphore_t *s);
void up(semaphore_t *s);

#endif
test_mutex.cC / 54 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "mutex.h"

enum {
    pause_seconds = 1
};

typedef struct {
    int val;
    int x;
} data_t;

static void *worker_thread(void *data)
{
    data_t *d = data;

    while (1) {
        lock(&d->val);
        d->x++;
        unlock(&d->val);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i, n;
    pthread_t t;
    data_t d;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
        return 1;
    }
    n = atoi(argv[1]);

    d.val = 0;
    d.x = 0;

    for (i = 0; i < n; i++)
        pthread_create(&t, NULL, worker_thread, &d);

    while (1) {
        printf("%d\n", d.x);
        sleep(pause_seconds);
    }

    return 0;
}
test_semaphore.cC / 56 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "semaphore.h"

enum {
    pause_seconds = 1
};

typedef struct {
    semaphore_t s;
    int x;
} data_t;

static void *worker_thread(void *data)
{
    data_t *d = data;

    while (1) {
        down(&d->s);
        d->x++;
        up(&d->s);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i, n;
    pthread_t t;
    data_t d;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
        return 1;
    }
    n = atoi(argv[1]);

    init(&d.s, 1);
    d.x = 0;

    for (i = 0; i < n; i++)
        pthread_create(&t, NULL, worker_thread, &d);

    while (1) {
        down(&d.s);
        printf("%d\n", d.x);
        up(&d.s);
        sleep(pause_seconds);
    }

    return 0;
}

Wait-For Graphs and Transactions

A wait-for graph represents processes and resources as two kinds of vertices. An edge from a resource to a process records ownership; an edge from a process to a resource records waiting.

A directed cycle identifies a deadlock when each resource instance is exclusive. Graph reduction removes edges belonging to participants that can finish and release what they own; if edges remain but none can be removed, the remaining participants are deadlocked.

Database systems can recover by grouping changes into transactions. A transaction records enough information to roll back its partial work. When deadlock detection finds a cycle, the system can choose a victim, roll it back, release its resources, and retry it later.

A transaction is not merely a long critical section: it may enter many small protected regions, acquire logical records over time, and undo its work if it cannot complete.

Detailed notes - 7.2.3: Resource Allocation Graphs

1

graph described in the book has process nodes and resource nodes

  • resource -> process: resource is held exclusively by that process
  • process -> resource: process waits to acquire that resource
  • for single-instance exclusive resources, a directed cycle indicates deadlock
  • often called a resource-allocation graph; book calls it a waiting graph

2

examples distinguish a graph without a wait cycle from:

  • two processes each waiting for the other's resource
  • five philosophers each waiting for the next fork in the ring

3

reduce the graph by repeatedly removing edges:

  • leaving a node with no incoming edges
  • entering a node with no outgoing edges
  • a remaining irreducible directed cycle identifies the deadlocked dependency

4

transactions allow recovery when avoiding every deadlock is impractical

  • retain information needed to undo modifications until completion
  • rollback restores the transaction's changes and releases its claims
  • graph can track transactions instead of whole processes
  • on a cycle, choose a victim using rollback cost; abort it and recheck
  • transaction may span many short critical sections
  • database lock bookkeeping avoids requiring one permanent mutex per record

Thread A owns lock 1 and waits for lock 2,
while thread B owns lock 2 and waits for lock 1,
forming a directed deadlock cycle.

Readers and Writers

Many readers may safely inspect one stable data set together. A writer, however, must exclude every reader and every other writer.

A reader-preference solution uses:

void read_data(void)
{
    pthread_mutex_lock(&reader_count_mutex);
    reader_count++;
    if (reader_count == 1)
        sem_wait(&data_access);
    pthread_mutex_unlock(&reader_count_mutex);

    /* read shared data */

    pthread_mutex_lock(&reader_count_mutex);
    reader_count--;
    if (reader_count == 0)
        sem_post(&data_access);
    pthread_mutex_unlock(&reader_count_mutex);
}

void write_data(void)
{
    sem_wait(&data_access);
    /* modify shared data */
    sem_post(&data_access);
}

The first reader acquires data_access; the last reader releases it. That cross-thread release is why a semaphore, rather than an owner-tracking mutex, fills this role.

This version can starve writers because a continuous stream of new readers can keep reader_count above zero forever. An entry gate prevents new readers from overtaking a writer after that writer has acquired the gate: the readers already inside eventually leave.

/* reader entry */
pthread_mutex_lock(&entry_gate);
pthread_mutex_unlock(&entry_gate);
/* then use the reader-count protocol */

/* writer */
pthread_mutex_lock(&entry_gate);
sem_wait(&data_access);
/* modify shared data */
sem_post(&data_access);
pthread_mutex_unlock(&entry_gate);

Real libraries often provide reader-writer locks, but the fairness policy is part of their semantics and must be checked rather than assumed. The entry-gate version likewise relies on the gate implementation eventually allowing a waiting writer to acquire it.

Detailed notes - 7.2.4: Readers and Writers

1

allow several readers at once, but make writers exclusive

  • reader + reader: compatible
  • writer + reader or writer + writer: conflict
  • even a read-only computation needs protection against concurrent modification

2

shared rc counts active readers

  • first reader acquires database access; last reader releases it
  • these may be different threads -> use binary semaphore db_access, initially 1
  • rc starts at 0; mutex rc_mutex starts unlocked and protects changes to rc

3

writer: down(db_access); modify data; up(db_access)

4

reader entry:

  • lock(rc_mutex); increment rc
  • if rc becomes 1, down(db_access) while still holding rc_mutex
  • unlock(rc_mutex), then read shared data
  • later readers join the group without acquiring db_access separately
  • exit: lock(rc_mutex); decrement rc
  • if rc becomes 0, up(db_access); unlock(rc_mutex)

5

continuous overlapping readers can keep rc above zero indefinitely

  • no individual reader need be slow
  • writer still waits forever for the whole reader group to disappear

6

add barrier mutex to stop admitting new readers once a writer owns it

  • reader briefly locks and unlocks barrier before the normal entry procedure
  • writer locks barrier before waiting on db_access
  • after barrier is acquired, only already-admitted readers can remain ahead

7

writer waits for admitted readers to finish, writes, then releases db_access and barrier

  • new readers can then enter again
  • prevents an endless influx of new readers from extending the current read phase
  • absolute starvation freedom still depends on fair enough lock acquisition / scheduling

Several readers overlap in time,
while a writer waits for all readers to leave and
then receives exclusive access.

Continuous reader cohorts can starve a writer; an admission gate prevents new readers extending the current cohort.
Reader overlap can keep a writer waiting. Open full size - Editable SVG
Section test (1 file) - 7.2.4: Readers and Writers
Section test04 (07-02)In catalog
readers-writers-00.cC / 128 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum {
    num_readers = 10,
    num_writers = 2
};

typedef struct {
    sem_t data_sem;
    sem_t db_access;
    pthread_mutex_t rc_mutex;
    pthread_mutex_t barrier;
    int i;
    int var;
    int rc;
} data_t;

static void data_init(data_t *d)
{
    sem_init(&d->data_sem, 0, 0);
    sem_init(&d->db_access, 0, 1);
    pthread_mutex_init(&d->rc_mutex, NULL);
    pthread_mutex_init(&d->barrier, NULL);
    d->var = 0;
    d->rc = 0;
}

static void data_destroy(data_t *d)
{
    sem_destroy(&d->data_sem);
    sem_destroy(&d->db_access);
    pthread_mutex_destroy(&d->rc_mutex);
    pthread_mutex_destroy(&d->barrier);
}

static void *reader(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        pthread_mutex_lock(&d->barrier);
        pthread_mutex_unlock(&d->barrier);

        pthread_mutex_lock(&d->rc_mutex);
        d->rc++;
        if (d->rc == 1)
            sem_wait(&d->db_access);
        pthread_mutex_unlock(&d->rc_mutex);

        printf("%d reads %d\n", i, d->var);

        pthread_mutex_lock(&d->rc_mutex);
        d->rc--;
        if (d->rc == 0)
            sem_post(&d->db_access);
        pthread_mutex_unlock(&d->rc_mutex);
        sleep(1);
    }

    return NULL;
}

static void *writer(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        pthread_mutex_lock(&d->barrier);
        sem_wait(&d->db_access);

        d->var++;
        printf("%d writes %d\n", i, d->var);

        sem_post(&d->db_access);
        pthread_mutex_unlock(&d->barrier);

        sleep(2);
    }

    return NULL;
}

int main()
{
    int i, failed;
    pthread_t tr[num_readers];
    pthread_t tw[num_writers];
    data_t d;

    data_init(&d);

    for (i = 0; i < num_readers; i++) {
        d.i = i;
        failed = pthread_create(&tr[i], NULL, reader, &d);
        if (failed) {
            fprintf(stderr, "pthread_create failed\n");
            return 1;
        }
        sem_wait(&d.data_sem);
    }

    for (i = 0; i < num_writers; i++) {
        d.i = i;
        failed = pthread_create(&tw[i], NULL, writer, &d);
        if (failed) {
            fprintf(stderr, "pthread_create failed\n");
            return 1;
        }
        sem_wait(&d.data_sem);
    }

    for (i = 0; i < num_readers; i++)
        pthread_join(tr[i], NULL);
    for (i = 0; i < num_writers; i++)
        pthread_join(tw[i], NULL);

    data_destroy(&d);

    return 0;
}

The Sleeping Barber

The sleeping-barber problem models one server, a finite waiting room, and clients that either wait or leave. It combines capacity counting, exclusive state, and event handoffs.

State or primitive Role
free_seats Number of available waiting-room seats
seats_mutex Protects free_seats and admission decisions
customers Counts admitted clients; the barber waits here when idle
barber_ready Invites one waiting client to the service chair
client_ready Confirms that the invited client is in position
service_done Prevents that client from leaving before service completes
chair_empty Confirms that the client left before the next invitation

Every transition that changes the meaning of free_seats must be coordinated with the corresponding notification. Otherwise two clients may reserve one seat, a barber may sleep while a client waits, or service may begin with no client in position.

Descriptions that hide the behavior of "perform service" in two independent procedures are incomplete unless they state how client and barber rendezvous at the beginning and end. The lesson is broader than this example: synchronization protocols must specify the entire handoff, not only the counters that look important at first glance.

A solution with POSIX semaphores and a mutex for the seat count. customers counts waiting clients and wakes the barber; barber, client and seat_belt hand one haircut from one side to the other. The messages decide from sem_getvalue whether someone was waiting, which is only a snapshot: the value can change right after the call.

Show the complete program
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

#define SLEEP_LIMIT 15.0

enum {
    num_seats = 4,
    num_clients = 6
};

typedef void *(*callback_t)(void*);

typedef struct {
    sem_t data_sem;
    int seats;
    pthread_mutex_t seats_mutex;
    sem_t customers;
    sem_t barber;
    sem_t client;
    sem_t seat_belt;
    int i;
} data_t;

static void data_init(data_t *d)
{
    sem_init(&d->data_sem, 0, 0);
    d->seats = num_seats;
    pthread_mutex_init(&d->seats_mutex, NULL);
    sem_init(&d->customers, 0, 0);
    sem_init(&d->barber, 0, 0);
    sem_init(&d->client, 0, 0);
    sem_init(&d->seat_belt, 0, 0);
}

static void data_destroy(data_t *d)
{
    sem_destroy(&d->data_sem);
    pthread_mutex_destroy(&d->seats_mutex);
    sem_destroy(&d->customers);
    sem_destroy(&d->barber);
    sem_destroy(&d->client);
    sem_destroy(&d->seat_belt);
}

static int random_number(double limit)
{
    return 1 + (int)(limit * rand() / (RAND_MAX + 1.0));
}

static void *barber(void *data)
{
    int num_customers;
    data_t *d = data;

    while (1) {
        sem_getvalue(&d->customers, &num_customers);
        if (num_customers == 0)
            printf("barber is going to sleep\n");
        sem_wait(&d->customers);

        pthread_mutex_lock(&d->seats_mutex);
        sem_post(&d->barber);
        if (num_customers != 0)
            d->seats++;
        pthread_mutex_unlock(&d->seats_mutex);

        sem_wait(&d->client);
        printf("barber is working\n");
        sem_post(&d->seat_belt);

        sleep(1);
    }

    return NULL;
}

static void *client(void *data)
{
    int num_customers;
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        pthread_mutex_lock(&d->seats_mutex);
        if (d->seats > 0) {
            sem_getvalue(&d->customers, &num_customers);
            if (num_customers == 0)
                printf("client %d is waking barber\n", i);
            sem_post(&d->customers);
            if (num_customers != 0)
                d->seats--;
            pthread_mutex_unlock(&d->seats_mutex);

            sem_wait(&d->barber);

            printf("haircut for client %d starts\n", i);
            sem_post(&d->client);
            sem_wait(&d->seat_belt);
        } else
            pthread_mutex_unlock(&d->seats_mutex);

        sleep(10 * random_number(SLEEP_LIMIT));
    }

    return NULL;
}

static void create_thread(pthread_t *t, callback_t callback, data_t *d)
{
    int failed = pthread_create(t, NULL, callback, d);
    if (failed) {
        fprintf(stderr, "pthread_create failed\n");
        exit(1);
    }
}

int main()
{
    int i;
    pthread_t tb;
    pthread_t tc[num_clients];
    data_t d;

    data_init(&d);

    create_thread(&tb, barber, &d);

    for (i = 0; i < num_clients; i++) {
        d.i = i;
        create_thread(&tc[i], client, &d);
        sem_wait(&d.data_sem);
    }

    pthread_join(tb, NULL);
    for (i = 0; i < num_clients; i++)
        pthread_join(tc[i], NULL);

    data_destroy(&d);

    return 0;
}
$ ./barber
barber is going to sleep
client 0 is waking barber
haircut for client 0 starts
barber is working
client 1 is waking barber
haircut for client 1 starts
barber is working
haircut for client 2 starts
barber is working
...

main passes each client its number through d.i and waits on data_sem until the thread has copied it, so the next iteration cannot overwrite the value too early.

Detailed notes - 7.2.5: The Sleeping Barber

1

one barber, one work chair, and N waiting-room chairs

  • clients and barber represent concurrent participants

2

barber finishes one client, then takes another waiting client

  • sleeps when no clients are waiting

3

arriving client wakes an idle barber

  • if barber is occupied, waits in a free waiting-room chair
  • leaves without service if no waiting seat is available

4

checking a condition and acting on it are separate operations

  • two arrivals can both observe the final free seat
  • without exclusion, both attempt to claim it

5

lost coordination example:

  • arriving client sees busy barber and starts toward waiting room
  • barber finishes, sees room still empty, and sleeps
  • client sits and waits for barber
  • both can wait indefinitely unless another arrival intervenes

6

common solution needs seat count, protected by a mutex, plus customer/barber semaphores

  • fuller version also coordinates entering the work chair and finishing the haircut
  • barber must not work before the client is ready
  • client must not leave before the work is finished

7

shared state:

  • seats = N; seats_mutex initially unlocked
  • customers: count of waiting clients
  • barber: permission for one client to approach the work chair
  • client: client signals that preparation is complete
  • seat_belt: barber signals completion
  • all four semaphores initially 0

8

barber loop:

  • down(customers)
  • lock(seats_mutex); up(barber); increment seats; unlock(seats_mutex)
  • down(client); perform haircut; up(seat_belt)
  • sleep for lack of clients happens through customers, not polling

9

inviting a client and updating free-seat count are coordinated under seats_mutex

  • other arrivals should observe a consistent allocation of waiting places
  • separating these changes exposes intermediate states to their seat checks

10

client:

  • lock(seats_mutex)
  • if no seat: unlock and leave
  • otherwise up(customers), decrement seats, unlock
  • down(barber); prepare in the work chair; up(client)
  • down(seat_belt) before leaving
  • one posted barber permit admits one waiting client

11

this client also announces itself through customers inside seats_mutex

  • extra client / seat_belt handshakes change which race arguments apply
  • justification must match the actual version of the algorithm

12

fuller model assumes a passive client during the haircut

  • useful when barber alone acts on a resource associated with the client
  • if both sides must actively work, blocking client for the whole operation is unsuitable
  • shorter textbook form calls BARBER_WORK and CUSTOMER_WORK concurrently
  • then those procedures must contain their own preparation/completion synchronization

13

assume BARBER_WORK / CUSTOMER_WORK handle their own rendezvous correctly

  • announcing a client before safely reserving a seat is still wrong
  • client may announce, discover no seat, then decide to leave
  • barber may consume the announcement before it can be withdrawn
  • result: invite / try to serve a nonexistent client

14

reserving a seat first and posting customers afterward needs separate analysis

  • earlier argument against announcing before reservation does not apply directly

15

literal story details are not all represented by the semaphore model

  • concurrent up(customers) calls are valid; each records one customer
  • barber may briefly sleep after a seat is reserved but before its customer is posted
  • eventual post still wakes it; holding seats_mutex alone does not forbid this pause
  • exact "who woke whom" and chair movement need extra state if those details matter

16

author's revision history illustrates why synchronization explanations need precision

  • adding a handshake can remove the very race used to justify another ordering
  • compare complete protocols, including assumptions hidden inside work procedures

The core protocol is:

The sleeping-barber protocol hands one client from the waiting room to the
barber through distinct invitation,
readiness, completion, and chair-empty synchronization events.

Four semaphore handshakes coordinate a waiting client, work-chair preparation and completion.
A haircut needs both admission and completion signals. Open full size - Editable SVG
Tests & experiments (3 files) - 7.2.5: The Sleeping Barber
Section test05 (07-02)In catalog
barber-00.cC / 118 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum {
    num_seats = 4,
    num_clients = 6
};

typedef void *(*callback_t)(void*);

typedef struct {
    sem_t data_sem;
    int seats;
    pthread_mutex_t seats_mutex;
    sem_t customers;
    sem_t barber;
    int i;
} data_t;

static void data_init(data_t *d)
{
    sem_init(&d->data_sem, 0, 0);
    d->seats = num_seats;
    pthread_mutex_init(&d->seats_mutex, NULL);
    sem_init(&d->customers, 0, 0);
    sem_init(&d->barber, 0, 0);
}

static void data_destroy(data_t *d)
{
    sem_destroy(&d->data_sem);
    pthread_mutex_destroy(&d->seats_mutex);
    sem_destroy(&d->customers);
    sem_destroy(&d->barber);
}

static void *barber(void *data)
{
    data_t *d = data;

    while (1) {
        sem_wait(&d->customers);

        pthread_mutex_lock(&d->seats_mutex);
        sem_post(&d->barber);
        d->seats++;
        pthread_mutex_unlock(&d->seats_mutex);

        printf("barber is working\n");

        sleep(1);
    }

    return NULL;
}

static void *client(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        pthread_mutex_lock(&d->seats_mutex);
        if (d->seats > 0) {
            sem_post(&d->customers);
            d->seats--;
            pthread_mutex_unlock(&d->seats_mutex);

            sem_wait(&d->barber);

            printf("haircut for client %d starts\n", i);
        } else
            pthread_mutex_unlock(&d->seats_mutex);

        sleep(2);
    }

    return NULL;
}

static void create_thread(pthread_t *t, callback_t callback, data_t *d)
{
    int failed = pthread_create(t, NULL, callback, d);
    if (failed) {
        fprintf(stderr, "pthread_create failed\n");
        exit(1);
    }
}

int main()
{
    int i, failed;
    pthread_t tb;
    pthread_t tc[num_clients];
    data_t d;

    data_init(&d);

    create_thread(&tb, barber, &d);

    for (i = 0; i < num_clients; i++) {
        d.i = i;
        create_thread(&tc[i], client, &d);
        sem_wait(&d.data_sem);
    }

    pthread_join(tb, NULL);
    for (i = 0; i < num_clients; i++)
        pthread_join(tc[i], NULL);

    data_destroy(&d);

    return 0;
}
barber-01.cC / 127 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

enum {
    num_seats = 4,
    num_clients = 6
};

typedef void *(*callback_t)(void*);

typedef struct {
    sem_t data_sem;
    int seats;
    pthread_mutex_t seats_mutex;
    sem_t customers;
    sem_t barber;
    sem_t client;
    sem_t seat_belt;
    int i;
} data_t;

static void data_init(data_t *d)
{
    sem_init(&d->data_sem, 0, 0);
    d->seats = num_seats;
    pthread_mutex_init(&d->seats_mutex, NULL);
    sem_init(&d->customers, 0, 0);
    sem_init(&d->barber, 0, 0);
    sem_init(&d->client, 0, 0);
    sem_init(&d->seat_belt, 0, 0);
}

static void data_destroy(data_t *d)
{
    sem_destroy(&d->data_sem);
    pthread_mutex_destroy(&d->seats_mutex);
    sem_destroy(&d->customers);
    sem_destroy(&d->barber);
    sem_destroy(&d->client);
    sem_destroy(&d->seat_belt);
}

static void *barber(void *data)
{
    data_t *d = data;

    while (1) {
        sem_wait(&d->customers);

        pthread_mutex_lock(&d->seats_mutex);
        sem_post(&d->barber);
        d->seats++;
        pthread_mutex_unlock(&d->seats_mutex);

        sem_wait(&d->client);
        printf("barber is working\n");
        sleep(1);
        sem_post(&d->seat_belt);
    }

    return NULL;
}

static void *client(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        pthread_mutex_lock(&d->seats_mutex);
        if (d->seats > 0) {
            sem_post(&d->customers);
            d->seats--;
            pthread_mutex_unlock(&d->seats_mutex);

            sem_wait(&d->barber);

            printf("haircut for client %d starts\n", i);
            sem_post(&d->client);
            sem_wait(&d->seat_belt);
        } else
            pthread_mutex_unlock(&d->seats_mutex);

        sleep(2);
    }

    return NULL;
}

static void create_thread(pthread_t *t, callback_t callback, data_t *d)
{
    int failed = pthread_create(t, NULL, callback, d);
    if (failed) {
        fprintf(stderr, "pthread_create failed\n");
        exit(1);
    }
}

int main()
{
    int i, failed;
    pthread_t tb;
    pthread_t tc[num_clients];
    data_t d;

    data_init(&d);

    create_thread(&tb, barber, &d);

    for (i = 0; i < num_clients; i++) {
        d.i = i;
        create_thread(&tc[i], client, &d);
        sem_wait(&d.data_sem);
    }

    pthread_join(tb, NULL);
    for (i = 0; i < num_clients; i++)
        pthread_join(tc[i], NULL);

    data_destroy(&d);

    return 0;
}
barber-02.cC / 145 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

#define SLEEP_LIMIT 15.0

enum {
    num_seats = 4,
    num_clients = 6
};

typedef void *(*callback_t)(void*);

typedef struct {
    sem_t data_sem;
    int seats;
    pthread_mutex_t seats_mutex;
    sem_t customers;
    sem_t barber;
    sem_t client;
    sem_t seat_belt;
    int i;
} data_t;

static void data_init(data_t *d)
{
    sem_init(&d->data_sem, 0, 0);
    d->seats = num_seats;
    pthread_mutex_init(&d->seats_mutex, NULL);
    sem_init(&d->customers, 0, 0);
    sem_init(&d->barber, 0, 0);
    sem_init(&d->client, 0, 0);
    sem_init(&d->seat_belt, 0, 0);
}

static void data_destroy(data_t *d)
{
    sem_destroy(&d->data_sem);
    pthread_mutex_destroy(&d->seats_mutex);
    sem_destroy(&d->customers);
    sem_destroy(&d->barber);
    sem_destroy(&d->client);
    sem_destroy(&d->seat_belt);
}

static int random_number(double limit)
{
    return 1 + (int)(limit * rand() / (RAND_MAX + 1.0));
}

static void *barber(void *data)
{
    int num_customers;
    data_t *d = data;

    while (1) {
        sem_getvalue(&d->customers, &num_customers);
        if (num_customers == 0)
            printf("barber is going to sleep\n");
        sem_wait(&d->customers);

        pthread_mutex_lock(&d->seats_mutex);
        sem_post(&d->barber);
        if (num_customers != 0)
            d->seats++;
        pthread_mutex_unlock(&d->seats_mutex);

        sem_wait(&d->client);
        printf("barber is working\n");
        sem_post(&d->seat_belt);

        sleep(1);
    }

    return NULL;
}

static void *client(void *data)
{
    int num_customers;
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        pthread_mutex_lock(&d->seats_mutex);
        if (d->seats > 0) {
            sem_getvalue(&d->customers, &num_customers);
            if (num_customers == 0)
                printf("client %d is waking barber\n", i);
            sem_post(&d->customers);
            if (num_customers != 0)
                d->seats--;
            pthread_mutex_unlock(&d->seats_mutex);

            sem_wait(&d->barber);

            printf("haircut for client %d starts\n", i);
            sem_post(&d->client);
            sem_wait(&d->seat_belt);
        } else
            pthread_mutex_unlock(&d->seats_mutex);

        sleep(10 * random_number(SLEEP_LIMIT));
    }

    return NULL;
}

static void create_thread(pthread_t *t, callback_t callback, data_t *d)
{
    int failed = pthread_create(t, NULL, callback, d);
    if (failed) {
        fprintf(stderr, "pthread_create failed\n");
        exit(1);
    }
}

int main()
{
    int i, failed;
    pthread_t tb;
    pthread_t tc[num_clients];
    data_t d;

    data_init(&d);

    create_thread(&tb, barber, &d);

    for (i = 0; i < num_clients; i++) {
        d.i = i;
        create_thread(&tc[i], client, &d);
        sem_wait(&d.data_sem);
    }

    pthread_join(tb, NULL);
    for (i = 0; i < num_clients; i++)
        pthread_join(tc[i], NULL);

    data_destroy(&d);

    return 0;
}

POSIX Threads

What a Thread Owns

POSIX threads are created inside one ordinary process. The initial thread and every created thread share most process resources.

Shared by threads in one process Distinct for each thread
Address space and global data Register state and instruction position
Heap and memory mappings Stack
Open file descriptors Thread identifier
Current directory and process id Scheduling state and selected signal-mask state

Even a thread's stack lies inside the common address space. Another thread can technically address it, so passing a pointer to a local object is safe only while that object's lifetime and concurrent access are correctly controlled.

Threads share the heap: memory allocated by one thread can be used and freed by another. A semaphore makes the second thread wait until the pointer is set:

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

typedef struct {
    int *p;
    sem_t ready;
} data_t;

static void data_init(data_t *d)
{
    sem_init(&d->ready, 0, 0);
}

static void data_destroy(data_t *d)
{
    sem_destroy(&d->ready);
}

void *thread1(void *data)
{
    data_t *d = data;

    d->p = malloc(sizeof(*d->p));
    *d->p = 42;
    sem_post(&d->ready);
    return NULL;
}

void *thread2(void *data)
{
    data_t *d = data;

    sem_wait(&d->ready);
    printf("%d\n", *d->p);
    free(d->p);
    return NULL;
}

int main()
{
    pthread_t t1, t2;
    data_t d;

    data_init(&d);

    pthread_create(&t1, NULL, thread1, &d);
    pthread_create(&t2, NULL, thread2, &d);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    data_destroy(&d);

    return 0;
}
42
Detailed notes - 7.3: Multithreaded Programming in Unix

1

practical thread examples let us test shared-data synchronization concepts

  • book uses threads to demonstrate mutexes and semaphores
  • author's criticism of threads and System V IPC is a design preference

2

understand thread programming even when choosing another design

  • choosing an alternative should follow knowledge of its tradeoffs

3

threads belong to one process and share its virtual address space

  • main thread and worker threads can access the same ordinary objects
  • each thread has its own execution state and stack
  • kernel schedules threads independently
  • getpid / getppid return the same process identifiers across the process's threads

4

each thread's stack is still memory in the common address space

  • another thread can access a valid object there if given its address
  • separate stacks do not provide memory isolation
Section test (1 file) - 7.3: Multithreaded Programming in Unix
Section test00 (07-03)In catalog
threads-00.cC / 56 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

typedef struct {
    int *p;
    sem_t ready;
} data_t;

static void data_init(data_t *d)
{
    sem_init(&d->ready, 0, 0);
}

static void data_destroy(data_t *d)
{
    sem_destroy(&d->ready);
}

void *thread1(void *data)
{
    data_t *d = data;

    d->p = malloc(sizeof(*d->p));
    *d->p = 42;
    sem_post(&d->ready);
}

void *thread2(void *data)
{
    data_t *d = data;

    sem_wait(&d->ready);
    printf("%d\n", *d->p);
    free(d->p);
}

int main()
{
    pthread_t t1, t2;
    data_t d;

    data_init(&d);

    pthread_create(&t1, NULL, thread1, &d);
    pthread_create(&t2, NULL, thread2, &d);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    data_destroy(&d);

    return 0;
}

Thread Lifecycle

Include <pthread.h> and compile and link with -pthread.

void *worker(void *argument)
{
    /* work */
    return result_pointer;
}

Main lifecycle operations:

Function Purpose
pthread_create Start a thread at a void *(*)(void *) function
pthread_join Wait for a joinable thread and collect its result
pthread_detach Arrange automatic cleanup; the thread can no longer be joined
pthread_self Return the calling thread's identifier
pthread_exit End the calling thread and provide its result
pthread_cancel Request cancellation of another thread
int pthread_create(pthread_t *thread, pthread_attr_t *attr,
                   void *(*start)(void *), void *arg);
int pthread_join(pthread_t thread, void **result);
int pthread_detach(pthread_t thread);
pthread_t pthread_self(void);
void pthread_exit(void *result);
int pthread_cancel(pthread_t thread);

Most pthread functions return 0 on success and an error number on failure; they generally do not report failure through errno.

A joinable thread that terminates retains bookkeeping until another thread joins it. A detached thread releases that state automatically, but its result cannot be collected with pthread_join.

Cancellation is a request, not necessarily immediate destruction. With the usual deferred mode, it takes effect at a cancellation point. Cancelled code must still release locks and other resources, usually through cleanup handlers. Designing explicit shutdown and joining the worker is often easier to reason about.

Returning from a created thread's start function is like calling pthread_exit for that thread. Returning from main, however, terminates the process and therefore all of its threads.

The example below demonstrates both directions of the void * interface and makes ownership of the result explicit:

Show a thread argument and result handoff
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int x;
    int y;
} operands_t;

static void *add(void *pointer)
{
    operands_t *operands = pointer;
    int *sum = malloc(sizeof(*sum));

    if (sum == NULL)
        return NULL;
    *sum = operands->x + operands->y;
    return sum;
}

int main(void)
{
    operands_t operands = { .x = 20, .y = 22 };
    pthread_t thread;
    void *result;

    if (pthread_create(&thread, NULL, add, &operands) != 0)
        return 1;
    if (pthread_join(thread, &result) != 0)
        return 1;
    if (result == NULL)
        return 1;

    printf("%d + %d = %d\n", operands.x, operands.y, *(int *)result);
    free(result);
    return 0;
}
cc -Wall -Wextra -pthread pthread-result.c -o pthread-result
./pthread-result

operands remains alive until pthread_join returns. The worker owns the allocated result while it runs; after the join, ownership passes to main, which frees it. The same lifetime rule applies to dynamically allocated shared state: unlock the shared mutex, join its final possible user, destroy the mutex, and only then free the containing object.

Detailed notes - 7.3.1: The POSIX Threads Library

1

POSIX standardized thread interfaces under the name POSIX Threads / pthreads

  • common portable interface for Unix thread programming

2

thread entry function has form void *entry(void *arg)

  • one arbitrary pointer supplies startup information
  • returned pointer supplies a result
  • referenced objects must remain valid for as long as they are used

3

pthread_create(&thread, attributes, entry, argument): start a thread

  • pthread_t stores its identifier
  • attributes = NULL selects defaults
  • entry receives argument as its one void* parameter
  • returns 0 on success, otherwise an error number directly
  • EAGAIN can mean exhausted resources / thread limit; other errors are possible

4

thread finishes by returning from its entry function or calling pthread_exit(result)

  • both provide a void* result to a joining thread
  • pthread_exit ends the calling thread
  • exit, or returning from the process's main function, ends the whole process

5

pthread_join(thread, &result): wait for a joinable thread to finish

  • result argument is an address of a void* variable
  • receives the thread's returned value
  • join also reclaims the terminated thread's retained resources

6

joinable thread retains termination information until joined

  • pthread_detach(thread) arranges automatic cleanup on termination
  • detached thread cannot later be joined for its result
  • join / detach return 0 or an error number

7

pthread_self(): obtain caller's pthread_t

  • pthread_detach(pthread_self()): detach the calling thread

8

pthread_cancel(thread): request cancellation

  • cancellation is not necessarily immediate
  • with deferred cancellation, request is acted on at a cancellation point
  • joined result is PTHREAD_CANCELED if cancellation terminates the thread
  • cancellation state, cleanup, and held resources require careful handling

A joinable thread retains its result until another thread joins it,
whereas a detached thread is cleaned up automatically when it exits.

Section test (1 file) - 7.3.1: The POSIX Threads Library
Section test01 (07-03)In catalog
pthreads-00.cC / 47 lines
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <pthread.h>


typedef struct {
    int x;
    int y;
} data_t;

void *thread_main(void *data)
{
    data_t *d = data;
    int *res;

    res = malloc(sizeof(int));
    *res = d->x + d->y;

    return res;
}

int main(int argc, char **argv)
{
    int failed, *z;
    void *res;
    pthread_t t;
    data_t d;

    if (argc < 3) {
        fprintf(stderr, "Usage: %s <x> <y>\n", argv[0]);
        return 1;
    }
    d.x = atoi(argv[1]);
    d.y = atoi(argv[2]);

    failed = pthread_create(&t, NULL, thread_main, &d);
    if (failed)
        err(1, "pthread");

    pthread_join(t, &res);
    z = res;

    printf("%d + %d = %d\n", d.x, d.y, *z);

    return 0;
}

POSIX Mutex API

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_destroy(pthread_mutex_t *mutex);

pthread_mutex_trylock normally reports EBUSY when another thread owns the mutex. Destroy a mutex only when it is unlocked and no thread can still access or wait on it.

For dynamically configured mutexes, use pthread_mutex_init with a mutex attribute object. Different mutex types can detect selected mistakes or support special behavior, but a normal mutex with simple ownership is the usual default.

Detailed notes - 7.3.2: Semaphores and Mutexes

1

POSIX mutex and semaphore interfaces use different naming conventions

  • mutex functions use pthread_ prefix
  • semaphore functions use sem_ and also support suitable interprocess use

2

pthread_mutex_t represents a mutex

  • initialize ordinary static/default mutex with PTHREAD_MUTEX_INITIALIZER
  • example: pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER
  • macro is an initializer, not an arbitrary assignment expression
  • other initialization forms allow attributes

3

mutex functions take pthread_mutex_t*:

  • pthread_mutex_lock: wait until acquired
  • pthread_mutex_trylock: attempt without waiting
  • pthread_mutex_unlock: owner releases it
  • return 0 or an error number directly
  • busy trylock reports EBUSY, not the book's stated EAGAIN
  • pthread_mutex_destroy ends the mutex's lifetime
  • destroy only when unlocked and no thread can still use or wait on it
  • do not rely on the implementation detecting every invalid destruction

4

sem_t represents a POSIX semaphore

  • interfaces are intended for threads and, when supported/configured, separate processes

5

process-shared semaphore support depends on implementation

  • semaphore object must live in shared memory
  • initialization must request process sharing

6

sem_init(&sem, pshared, value): initialize an unnamed semaphore

  • pshared = 0: shared by threads of one process
  • nonzero: shared by processes, requiring actual shared-memory placement
  • value: initial permit count
  • returns 0 or -1 with errno, unlike pthread error-number returns
  • implementations can use user-space fast paths and kernel waiting/wakeup

7

sem_post(&sem): add one permit, waking a waiter if needed

  • sem_wait(&sem): consume one permit, blocking while unavailable
  • sem_trywait(&sem): immediate attempt; at zero returns -1 with errno = EAGAIN
  • successful operations return 0
  • real code must also handle failures, including interrupted sem_wait

8

sem_getvalue(&sem, &value): obtain an observed semaphore value

  • another participant may change it immediately
  • reading the count does not reserve a permit

9

sem_destroy(&sem): end semaphore lifetime

  • no thread or process may still be waiting on it or using it
  • destroying a semaphore with waiters has undefined behavior
  • do not expect sem_destroy to detect this lifecycle error
Tests & experiments (3 files) - 7.3.2: Semaphores and Mutexes
Section test02 (07-03)In catalog
destroy-00.cC / 55 lines
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

struct Shared {
    pthread_mutex_t mutex;
};

struct Shared *shared;

void *worker(void *arg)
{
    printf("worker: trying to lock mutex...\n");

    // This thread may block here.
    pthread_mutex_lock(&shared->mutex);

    printf("worker: acquired mutex\n");

    pthread_mutex_unlock(&shared->mutex);
    return NULL;
}

int main(void)
{
    pthread_t thread;

    shared = malloc(sizeof(*shared));
    pthread_mutex_init(&shared->mutex, NULL);

    // Main thread takes the mutex first.
    pthread_mutex_lock(&shared->mutex);

    // Worker will now try to lock it and block.
    pthread_create(&thread, NULL, worker, NULL);

    sleep(1);

    printf("main: freeing object containing mutex!\n");

    // BUG:
    // worker is still waiting on shared->mutex,
    // but we destroy the memory containing that mutex.
    free(shared);

    // Program might NOT crash here.
    printf("main: still running...\n");

    sleep(2);

    printf("main: doing some unrelated work...\n");

    pthread_join(thread, NULL);
}
destroy-01.cC / 61 lines
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

struct Shared {
    pthread_mutex_t mutex;
};

struct Shared *shared;

void *worker(void *arg)
{
    printf("worker: trying to lock mutex...\n");

    pthread_mutex_lock(&shared->mutex);

    printf("worker: acquired mutex\n");

    // Do protected work here.

    pthread_mutex_unlock(&shared->mutex);

    printf("worker: finished\n");
    return NULL;
}

int main(void)
{
    pthread_t thread;

    shared = malloc(sizeof(*shared));
    pthread_mutex_init(&shared->mutex, NULL);

    // Lock it before starting worker.
    pthread_mutex_lock(&shared->mutex);

    pthread_create(&thread, NULL, worker, NULL);

    sleep(1);

    printf("main: unlocking mutex\n");

    // Allow worker to proceed.
    pthread_mutex_unlock(&shared->mutex);

    // IMPORTANT:
    // Wait until worker is completely finished.
    pthread_join(thread, NULL);

    printf("main: worker is gone, safe to destroy mutex\n");

    // Nobody can use the mutex anymore.
    pthread_mutex_destroy(&shared->mutex);

    // Now it is safe to release the storage.
    free(shared);

    printf("main: done\n");
    return 0;
}
destroy-02.cC / 62 lines
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

struct Shared {
    pthread_mutex_t mutex;
};


void *worker(void *arg)
{
    struct Shared *shared = arg;
    printf("worker: trying to lock mutex...\n");

    // This thread may block here.
    pthread_mutex_lock(&shared->mutex);

    printf("worker: acquired mutex\n");

    pthread_mutex_unlock(&shared->mutex);
    return NULL;
}

int main(void)
{
    pthread_t thread;
    struct Shared *shared;

    shared = malloc(sizeof(*shared));
    pthread_mutex_init(&shared->mutex, NULL);

    // Main thread takes the mutex first.
    pthread_mutex_lock(&shared->mutex);

    // Worker will now try to lock it and block.
    pthread_create(&thread, NULL, worker, shared);

    sleep(1);

    printf("main: freeing object containing mutex!\n");

    pthread_mutex_unlock(&shared->mutex);

    pthread_join(thread, NULL);

    pthread_mutex_destroy(&shared->mutex);

    // BUG:
    // worker is still waiting on shared->mutex,
    // but we destroy the memory containing that mutex.
    free(shared);

    // Program might NOT crash here.
    printf("main: still running...\n");

    sleep(2);

    printf("main: doing some unrelated work...\n");

    return 0;
}

POSIX Semaphore API

POSIX unnamed semaphores use <semaphore.h> and the type sem_t:

int sem_init(sem_t *sem, int process_shared, unsigned int value);
int sem_wait(sem_t *sem);
int sem_trywait(sem_t *sem);
int sem_post(sem_t *sem);
int sem_getvalue(sem_t *sem, int *value);
int sem_destroy(sem_t *sem);

Unlike pthread mutex functions, these functions return -1 on failure and set errno. sem_trywait sets errno to EAGAIN when the count is zero.

When process_shared is zero, the semaphore synchronizes threads in one process. For a nonzero value, the semaphore must reside in memory shared by the participating processes and the platform must support process-shared semaphores.

Destroy a semaphore only after every possible user has stopped accessing it and no participant is waiting on it. Destroying a live synchronization object causes undefined behavior.

Passing Thread Arguments Safely

This common loop is wrong:

struct worker_args args;

for (i = 0; i < count; i++) {
    args.index = i;
    pthread_create(&threads[i], NULL, worker, &args);
}

Every worker receives the same address while the creating thread keeps changing the object. A worker may see a later iteration's value, a partially updated structure, or a C data race.

Safe ownership patterns include:

Pattern Lifetime rule
Array element per thread Keep the entire array alive until all workers have joined
Separately allocated argument Worker owns and eventually frees its argument
Start-up handshake Creator waits until worker copies the shared handoff structure
Immutable shared structure Construct fully before creation; never mutate while in use

Do not pass a pointer to a creator's local variable if the creator can return before the worker finishes with it.

Demonstration: Protecting an Invariant

The following program starts several threads. Every update increments one array element and decrements another, so the array sum must remain zero. The mutex protects that pair of operations as one critical section. Each worker also owns its pseudorandom-generator state; a shared generator would introduce another shared object and another contract to synchronize.

Show the complete demonstration
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

enum { array_size = 10, worker_count = 4, iterations = 2000000 };

#ifndef PROTECTION
#define PROTECTION 1
#endif

struct worker_args {
    int *array;
    unsigned int random_state;
};

static pthread_mutex_t array_mutex = PTHREAD_MUTEX_INITIALIZER;

static unsigned int next_random(unsigned int *state)
{
    *state = *state * 1103515245u + 12345u;
    return *state;
}

static void *worker(void *pointer)
{
    struct worker_args *args = pointer;
    int n;

    for (n = 0; n < iterations; n++) {
        int first, second;

        first = next_random(&args->random_state) % array_size;
        second = next_random(&args->random_state) % array_size;
        if (first == second)
            continue;

#if PROTECTION
        pthread_mutex_lock(&array_mutex);
#endif
        args->array[first]++;
        args->array[second]--;
#if PROTECTION
        pthread_mutex_unlock(&array_mutex);
#endif
    }
    return NULL;
}

int main(void)
{
    int array[array_size] = { 0 };
    pthread_t threads[worker_count];
    struct worker_args args[worker_count];
    int sum = 0;
    int i;

    for (i = 0; i < worker_count; i++) {
        args[i].array = array;
        args[i].random_state = 12345u + (unsigned int)i;
        if (pthread_create(&threads[i], NULL, worker, &args[i]) != 0) {
            fprintf(stderr, "pthread_create failed\n");
            exit(1);
        }
    }

    for (i = 0; i < worker_count; i++) {
        if (pthread_join(threads[i], NULL) != 0) {
            fprintf(stderr, "pthread_join failed\n");
            exit(1);
        }
    }

    for (i = 0; i < array_size; i++) {
        printf("%s%d", i == 0 ? "(" : ",", array[i]);
        sum += array[i];
    }
    printf(") sum=%d\n", sum);

    pthread_mutex_destroy(&array_mutex);
    return 0;
}
cc -Wall -Wextra -O2 -pthread balance.c -o balance
cc -Wall -Wextra -O2 -pthread -DPROTECTION=0 balance.c -o balance-unprotected

The protected program must finish with sum=0. The unprotected version deliberately contains C data races and therefore has undefined behavior; it often loses updates, but no particular output is guaranteed. This is a demonstration of the bug, not a valid way to test for its absence.

Detailed notes - 7.3.3: Demonstration Program

1

demonstration tests shared-data correctness rather than solving a useful application task

  • author's skepticism about threads motivates the choice of a deliberately simple example

2

main creates an integer array, initially all zeros

  • each worker repeatedly chooses two positions
  • increments one element and decrements another
  • expected invariant: sum of all elements remains zero
  • main prints the sum and array once per second

3

compile the same example with synchronization enabled or disabled

  • protected version should preserve the invariant and print consistent snapshots
  • unprotected updates can lose increments / decrements and corrupt the total
  • exact unprotected output is not predictable; unsynchronized C accesses are data races
  • correctness also assumes valid integer ranges and successful API calls

4

thread startup introduces a second shared-data problem

  • example therefore uses a semaphore as well as the array mutex

5

workers need independent pseudo-random generator state

  • a shared rand generator mixes requests according to unpredictable thread scheduling
  • safety of concurrent rand calls depends on the library implementation
  • even a synchronized global generator does not give each thread a reproducible sequence
  • private state avoids this shared generator dependency

6

book uses rand_r(&seed) with an unsigned int seed private to each worker

  • function updates caller-supplied state instead of one shared generator state
  • calling time separately in quickly started threads can give them identical seeds

7

main obtains time(NULL) once, then increments the seed for each new worker

  • different startup values produce different per-thread generator sequences
  • this is a simple demonstration setup, not a guarantee of independent random streams

8

startup information includes seed, shared array, and its mutex

  • pass these explicitly instead of relying on global variables

9

one void* can point to a structure containing all startup data

  • initial fields: unsigned int randseed, int *array, pthread_mutex_t *arr_mutex
  • fill the structure and pass its address as pthread_create's argument

10

startup race: worker reads the structure while main prepares the next worker

  • reusing the same structure can overwrite fields before the first worker copies them
  • passing a pointer does not copy the pointed-to object

11

one structure per worker is a possible alternative

  • each structure must remain alive until its user finishes reading it
  • resizing a contiguous array can invalidate addresses already handed to threads
  • stable allocation or a controlled lifetime is required

12

example instead uses a copy-and-acknowledge handshake

  • worker copies every startup field into its own local variables
  • then tells main it no longer uses the structure
  • main waits for that acknowledgment before modifying the structure again

13

startup semaphore initially 0

  • main starts worker, then sem_wait
  • worker finishes copying, then sem_post
  • posting before main begins waiting is safe: permit remains available
  • one ordinary POSIX semaphore suffices for this binary signaling pattern

14

example constants:

  • ARRAY_SIZE = 10
  • WORKERS_COUNT = 3
  • PAUSE_LENGTH = 1 second
  • PROTECTION defaults to 1; compiler definition can set it to 0

15

thread_start_data also receives sem_t *data_sem

  • array and seed fields are always present
  • mutex and semaphore pointers exist only under #if PROTECTION == 1

16

worker entry:

  • convert void* argument to thread_start_data*
  • copy seed, array pointer, and synchronization pointers locally
  • sem_post(data_sem) only after all copying is complete
  • repeatedly choose idx1 and idx2 using rand_r % ARRAY_SIZE
  • if indices match, skip the iteration
  • otherwise lock array mutex, increment one element, decrement the other, unlock
  • random-number generation stays outside the array's critical section
  • loop has no normal termination path; trailing return NULL is unreachable

17

main's local variables hold the shared array and startup structure

  • also holds pthread_t, array mutex, and startup semaphore
  • initialize every array element to zero
  • main remains alive, so these local objects outlive the workers' use of them

18

initialize startup structure once:

  • randseed = time(NULL)
  • array = the_array
  • arr_mutex and data_sem point to main's synchronization objects
  • sem_init(&tsd_sem, 0, 0): thread-shared, initially zero

19

worker creation loop:

  • increment tsdata.randseed
  • pthread_create(..., worker_thread, &tsdata)
  • when protection is enabled, sem_wait(&tsd_sem) before the next iteration
  • check creation success before waiting; otherwise a failed creation leaves no poster
  • real code must also handle interrupted waits and other synchronization errors

20

printing loop must observe one consistent state

  • lock arr_mutex
  • compute sum across all elements
  • print sum and those same element values
  • unlock mutex, then sleep(PAUSE_LENGTH)
  • locking only the summation would allow printed elements to belong to another state
  • an alternative design copies a snapshot under the lock and prints afterward

21

main also ends with an unreachable return 0 after its infinite loop

  • demonstration has no normal join / shutdown path
  • a finite application needs explicit worker termination and object cleanup

22

book supplies the complete example as balance.c

  • protected build: gcc -Wall -g balance.c -lpthread -o balance
  • unprotected build adds -DPROTECTION=0 and names output bal_noprot
  • conditional compilation removes both mutex protection and startup signaling

23

sample output shows zero totals with protection and drifting totals without it

  • total is printed first, followed by the array in parentheses
  • printed values and rates of corruption depend on execution order
  • observed failures illustrate the race; an apparently correct run cannot disprove it

24

older producer-consumer demonstration was corrected after errors were found

  • corrected example remains available as prod_cons.c in the book's examples

25

conclusion: hidden shared state can appear inside called library functions

  • global or static variables may be accessed by several calling threads
  • synchronization requirements must cover those objects too
  • concurrency bugs may remain invisible through ordinary testing

26

author favors threads only when independent computation gives a measured multicore benefit

  • also prefers process isolation where practical
  • treat this as the author's design position; evaluate the actual task's concurrency needs
Examples & tests (4 files) - 7.3.3: Demonstration Program
Book exampleBook example: balance.cIn catalog
balance.cC / 109 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <pthread.h>
#include <semaphore.h>

#define ARRAY_SIZE 10
#define WORKERS_COUNT 10
#define PAUSE_LENGTH 1

#ifndef PROTECTION
#define PROTECTION 1
#endif

struct thread_start_data {
    unsigned int randseed;
    int *array;
#if PROTECTION == 1
    pthread_mutex_t *arr_mutex;
    sem_t *data_sem;
#endif
};

static void *worker_thread(void *v_data)
{
    struct thread_start_data *data = v_data;
    unsigned int randseed = data->randseed;
    int *array = data->array;
#if PROTECTION == 1
    pthread_mutex_t *arr_mutex = data->arr_mutex;
    sem_t *data_sem = data->data_sem;
    sem_post(data_sem);  /* tell the main thread we don't need
                            the v_data structure anymore */
#endif
    for(;;) {
        int idx1, idx2;
        idx1 = rand_r(&randseed) % ARRAY_SIZE;
        idx2 = rand_r(&randseed) % ARRAY_SIZE;
        if(idx1 == idx2)
            continue;
#if PROTECTION == 1
        pthread_mutex_lock(arr_mutex);
#endif
        if(rand_r(&randseed) & 0x10) {
            array[idx1]++;
            array[idx2]--;
        } else {
            array[idx2]--;
            array[idx1]++;
        }
#if PROTECTION == 1
        pthread_mutex_unlock(arr_mutex);
#endif
    }
    return NULL;  /* never reached */
}


int main()
{
    int i;
    int the_array[ARRAY_SIZE];
    struct thread_start_data tsdata;
    pthread_t thr;
#if PROTECTION == 1
    pthread_mutex_t arr_mutex = PTHREAD_MUTEX_INITIALIZER;
    sem_t tsd_sem;
#endif

    for(i = 0; i < ARRAY_SIZE; i++)
        the_array[i] = 0;

    tsdata.randseed = time(NULL);
    tsdata.array = the_array;
#if PROTECTION == 1
    tsdata.arr_mutex = &arr_mutex;
    tsdata.data_sem = &tsd_sem;
    sem_init(&tsd_sem, 0, 0);
#endif

    for(i = 0; i < WORKERS_COUNT; i++) {
        tsdata.randseed++;
        pthread_create(&thr, NULL, worker_thread, &tsdata);
#if PROTECTION == 1
        sem_wait(&tsd_sem);
#endif
    }

    for(;;) {
        int sum;
#if PROTECTION == 1
        pthread_mutex_lock(&arr_mutex);
#endif
        sum = 0;
        for(i = 0; i < ARRAY_SIZE; i++)
            sum += the_array[i];
        printf("%d ", sum);
        for(i = 0; i < ARRAY_SIZE; i++)
            printf("%c%d", i ? ',' : '(', the_array[i]);
        printf(")\n");
#if PROTECTION == 1
        pthread_mutex_unlock(&arr_mutex);
#endif
        sleep(PAUSE_LENGTH);
    }
    return 0;
}
Section test03 (07-03)In catalog
parallel_count-00.cC / 100 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#define ARRAY_SIZE 10
#define WORKERS_COUNT 3
#define PAUSE_LENGTH 1
#ifndef PROTECTION
#define PROTECTION 1
#endif

struct thread_start_data {
    unsigned int randseed;
    int *array;
#if PROTECTION == 1
    pthread_mutex_t *arr_mutex;
    sem_t *data_sem;
#endif
};

static void *worker_thread(void *v_data)
{
    struct thread_start_data *data = v_data;
    unsigned int randseed = data->randseed;
    int *array = data->array;
#if PROTECTION == 1
    pthread_mutex_t *arr_mutex = data->arr_mutex;
    sem_t *data_sem = data->data_sem;
    sem_post(data_sem);
#endif
    for (;;) {
        int idx1, idx2;
        idx1 = rand_r(&randseed) % ARRAY_SIZE;
        idx2 = rand_r(&randseed) % ARRAY_SIZE;
        if (idx1 == idx2)
            continue;
#if PROTECTION == 1
        pthread_mutex_lock(arr_mutex);
#endif
        array[idx1]++;
        array[idx2]--;
#if PROTECTION == 1
        pthread_mutex_unlock(arr_mutex);
#endif
    }
    return NULL;
}

int main()
{
    int i;
    int the_array[ARRAY_SIZE];
    struct thread_start_data tsdata;
    pthread_t thr;
#if PROTECTION == 1
    pthread_mutex_t arr_mutex = PTHREAD_MUTEX_INITIALIZER;
    sem_t tsd_sem;
#endif
    for (i = 0; i < ARRAY_SIZE; i++)
        the_array[i] = 0;

    tsdata.randseed = time(NULL);
    tsdata.array = the_array;
#if PROTECTION == 1
    tsdata.arr_mutex = &arr_mutex;
    tsdata.data_sem = &tsd_sem;
    sem_init(&tsd_sem, 0, 0);
#endif

    for (i = 0; i < WORKERS_COUNT; i++) {
        tsdata.randseed++;
        pthread_create(&thr, NULL, worker_thread, &tsdata);
#if PROTECTION == 1
        sem_wait(&tsd_sem);
#endif
    }

    for (;;) {
        int sum;
#if PROTECTION == 1
        pthread_mutex_lock(&arr_mutex);
#endif
        sum = 0;
        for (i = 0; i < ARRAY_SIZE; i++)
            sum += the_array[i];
        printf("%d ", sum);
        for (i = 0; i < ARRAY_SIZE; i++)
            printf("%c%d", i ? ',' : '(', the_array[i]);
        printf(")\n");
#if PROTECTION == 1
        pthread_mutex_unlock(&arr_mutex);
#endif
        sleep(PAUSE_LENGTH);
    }

    return 0;
}
parallel_count-01.cC / 97 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#define ARRAY_SIZE 10
#define WORKERS_COUNT 10
#define PAUSE_LENGTH 1
#ifndef PROTECTION
#define PROTECTION 1
#endif

struct thread_start_data {
    unsigned int randseed;
    int *array;
#if PROTECTION == 1
    pthread_mutex_t *arr_mutex;
    sem_t *data_sem;
#endif
};

static void *worker_thread(void *v_data)
{
    struct thread_start_data *data = v_data;
    unsigned int randseed = data->randseed;
#if PROTECTION == 1
    sem_post(data->data_sem);
#endif
    for (;;) {
        int idx1, idx2;
        idx1 = rand_r(&randseed) % ARRAY_SIZE;
        idx2 = rand_r(&randseed) % ARRAY_SIZE;
        if (idx1 == idx2)
            continue;
#if PROTECTION == 1
        pthread_mutex_lock(data->arr_mutex);
#endif
        data->array[idx1]++;
        data->array[idx2]--;
#if PROTECTION == 1
        pthread_mutex_unlock(data->arr_mutex);
#endif
    }
    return NULL;
}

int main()
{
    int i;
    int the_array[ARRAY_SIZE];
    struct thread_start_data tsdata;
    pthread_t thr;
#if PROTECTION == 1
    pthread_mutex_t arr_mutex = PTHREAD_MUTEX_INITIALIZER;
    sem_t tsd_sem;
#endif
    for (i = 0; i < ARRAY_SIZE; i++)
        the_array[i] = 0;

    tsdata.randseed = time(NULL);
    tsdata.array = the_array;
#if PROTECTION == 1
    tsdata.arr_mutex = &arr_mutex;
    tsdata.data_sem = &tsd_sem;
    sem_init(&tsd_sem, 0, 0);
#endif

    for (i = 0; i < WORKERS_COUNT; i++) {
        tsdata.randseed++;
        pthread_create(&thr, NULL, worker_thread, &tsdata);
#if PROTECTION == 1
        sem_wait(&tsd_sem);
#endif
    }

    for (;;) {
        int sum;
#if PROTECTION == 1
        pthread_mutex_lock(&arr_mutex);
#endif
        sum = 0;
        for (i = 0; i < ARRAY_SIZE; i++)
            sum += the_array[i];
        printf("%d ", sum);
        for (i = 0; i < ARRAY_SIZE; i++)
            printf("%c%d", i ? ',' : '(', the_array[i]);
        printf(")\n");
#if PROTECTION == 1
        pthread_mutex_unlock(&arr_mutex);
#endif
        sleep(PAUSE_LENGTH);
    }

    return 0;
}
parallel_count-02.cC / 121 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

enum {
    array_size = 10,
    num_workers = 3,
    pause_length = 1
};

#ifndef PROTECTION
#define PROTECTION 1
#endif

typedef struct {
    unsigned int randseed;
    int array[array_size];
#if PROTECTION == 1
    pthread_mutex_t arr_mutex;
    sem_t data_sem;
#endif
} data_t;

static void data_init(data_t *d)
{
    int i;

    d->randseed = time(NULL);
    for (i = 0; i < array_size; i++)
        d->array[i] = 0;
#if PROTECTION == 1
    pthread_mutex_init(&d->arr_mutex, NULL);
    sem_init(&d->data_sem, 0, 0);
#endif
}

#if PROTECTION == 1
static void data_destroy(data_t *d)
{
    pthread_mutex_destroy(&d->arr_mutex);
    sem_destroy(&d->data_sem);
}
#endif

static void *worker_thread(void *data)
{
    int i1, i2;
    data_t *d = data;
    unsigned int randseed = d->randseed;
#if PROTECTION == 1
    sem_post(&d->data_sem);
#endif
    while (1) {
        i1 = rand_r(&randseed) % array_size;
        i2 = rand_r(&randseed) % array_size;
        if (i1 == i2)
            continue;
#if PROTECTION == 1
        pthread_mutex_lock(&d->arr_mutex);
#endif
        d->array[i1]++;
        d->array[i2]--;
#if PROTECTION == 1
        pthread_mutex_unlock(&d->arr_mutex);
#endif
    }
    return NULL;
}

static void print_sum(data_t *d)
{
    int i, sum;

    while (1) {
#if PROTECTION == 1
        pthread_mutex_lock(&d->arr_mutex);
#endif
        sum = 0;
        for (i = 0; i < array_size; i++)
            sum += d->array[i];
        printf("%d ", sum);
        for (i = 0; i < array_size; i++)
            printf("%c%d", i ? ',' : '(', d->array[i]);
        printf(")\n");
#if PROTECTION == 1
        pthread_mutex_unlock(&d->arr_mutex);
#endif
        sleep(pause_length);
    }
}

int main()
{
    int i;
    data_t d;
    pthread_t t[num_workers];

    data_init(&d);

    for (i = 0; i < num_workers; i++) {
        d.randseed++;
        pthread_create(&t[i], NULL, worker_thread, &d);
#if PROTECTION == 1
        sem_wait(&d.data_sem);
#endif
    }

    print_sum(&d);

    for (i = 0; i < num_workers; i++)
        pthread_join(t[i], NULL);

#if PROTECTION == 1
    data_destroy(&d);
#endif

    return 0;
}

Practical Locking Rules

Shared Data on Disk

Two unrelated programs can share data without sharing memory. A mailbox, accounting file, or database may be a shared object because the problem domain requires concurrent access. The same stale-read, invariant, deadlock, and starvation questions still apply.

Detailed notes - 7.4: Shared data on disk

1

shared disk data can be unavoidable even when shared memory is avoided

  • independent programs may need the same persistent information
  • author recommends avoiding concurrent file access where practical
  • otherwise choose a locking protocol understood by every participant

Advisory File Locking

Most Unix file locks are advisory. They record an agreement, but they do not prevent a process with ordinary file permissions from calling read or write without first taking a lock. Every cooperating program must use the same protocol.

Mechanism Managed by Granularity Main advantage Main weakness
Separate lock file Application and filesystem Usually whole file Simple; can work across varied environments Stale lock files and naming conventions
BSD flock Kernel Whole file Simple shared/exclusive operations Open-file-description semantics and portability
POSIX fcntl / lockf Kernel Byte ranges Fine-grained locks and optional owner query Surprising process-wide close semantics

Mandatory locking has existed on some systems, but it is not a portable basis for application design.

Network filesystems are especially important. Whether a lock is visible and atomic across machines depends on the operating system, filesystem, mount configuration, and protocol version. Document the requirement and verify it in the deployment environment.

Detailed notes - 7.4.1: Available file-locking mechanisms

1

file lock: a way to tell other processes that a file is in use

  • intended to prevent conflicting access during a critical section
  • acquiring a lock and blocking while waiting for one are different concepts

2

the book distinguishes the English word lock from blocking

  • informal Russian transliterations are common in conversation
  • an explicit term is needed for the written discussion

3

the author uses the Russian term meaning acquisition / capture for a lock

  • in these English notes, the term remains file lock

4

ordinary Unix file locks are advisory:

  • do not themselves prohibit ordinary reads and writes
  • a process with sufficient file permissions can ignore the locking protocol

5

all participants must cooperate:

  • acquire the appropriate lock before accessing protected data
  • a program unaware of the protocol can invalidate its guarantees
  • a user may unknowingly run such a program against the shared file

6

mandatory locking would enforce restrictions on ordinary I/O too

  • book describes historical Linux mount options and special mode bits
  • that mechanism was uncommon and problematic
  • the following discussion uses advisory locking

7

three approaches considered:

  • lock file: existence of an additional file indicates ownership
  • BSD locks: flock
  • traditional POSIX record locks: fcntl, also exposed through lockf
  • kernel-mediated requests reject or wait for conflicting locks

8

network filesystems add another layer of semantics:

  • locking depends on the filesystem, protocol, client, and server
  • do not assume local-filesystem behavior carries over unchanged
  • document the environments the program's protocol supports
  • the book's blanket warning about network locks is not a universal rule

9

author suggests configurable support for several locking mechanisms

  • participants must agree on which mechanisms and conventions to use
  • combining mechanisms also requires a consistent acquisition order
Tests & experiments (2 files) - 7.4.1: Available file-locking mechanisms
Section testmandatory (07-04-01)In catalog
MakefileMake / 12 lines
PROGRAMS = readv

CC = gcc
CFLAGS = -g -Wall

all: $(PROGRAMS)

$(PROGRAMS): %: %.c
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)
readv.cC / 43 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/uio.h>

int main()
{
    int fd, n;
    char buf1[6];
    char buf2[6];
    struct iovec iov[2];

    fd = open("readv.t", O_RDONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }

    buf1[6] = 0;
    buf2[6] = 0;

    iov[0].iov_base = buf1;
    iov[0].iov_len  = 5;

    iov[1].iov_base = buf2;
    iov[1].iov_len  = 5;

    n = readv(fd, iov, 2);

    if (n == -1) {
        perror("readv");
        close(fd);
        return 1;
    }

    printf("readv read %zd bytes\n", n);
    printf("buf1 = \"%s\"\n", buf1);
    printf("buf2 = \"%s\"\n", buf2);

    close(fd);
    return 0;
}

Lock Files with O_EXCL

A portable cooperative convention is to create a companion file atomically:

int acquire_lock_file(const char *name)
{
    int fd;

    for (;;) {
        fd = open(name, O_WRONLY | O_CREAT | O_EXCL, 0666);
        if (fd != -1) {
            close(fd);
            return 0;
        }
        if (errno != EEXIST)
            return -1;
        sleep(1);
    }
}

/* protected file work */

unlink("data.lock");

O_EXCL is essential: a separate "does the file exist?" check followed by creation has the same check-then-act race as an ordinary lock variable.

Lock-file limitations:

A more elaborate remote-filesystem protocol can create a unique temporary file and atomically link the agreed lock name to it, then inspect the hard-link count when a network error leaves the result uncertain.

Detailed notes - 7.4.2: Creating a separate lock file

1

lock-file protocol for foobar.dat:

  • attempt open("foobar.dat.lock", O_WRONLY|O_CREAT|O_EXCL, 0666)
  • success: close the descriptor; existence of the file retains the lock
  • -1 with EEXIST: another participant owns the lock; wait and retry
  • another error: handle it as an actual failure, not as lock contention
  • work on foobar.dat only after acquisition
  • unlink("foobar.dat.lock") when finished

2

analogy with a mutex:

  • atomically creating the lock file = acquire
  • removing it = release
  • checking for absence and then creating in separate operations is unsafe
  • older network implementations did not always provide atomic O_EXCL
  • correctness depends on the actual filesystem's guarantees

3

alternative when exclusive creation cannot be relied on:

  • create a uniquely named temporary file on the same filesystem
  • use link to create the agreed lock pathname pointing to that file
  • ownership is indicated by the hard link, not the temporary name alone
  • source suggests including process identity / time in the unique name

4

network errors can make the outcome of link ambiguous:

  • server may create the link but its success reply may be lost
  • after an error, stat the unique temporary file
  • st_nlink == 2 indicates that the second name was created

5

release by removing the agreed hard-link pathname

  • temporary file can be retained for reuse
  • remove the temporary file when it is no longer needed

6

advantages of this approach:

  • simple filesystem operations, without a special file-locking API
  • can work across some network filesystems with an appropriate protocol
  • still has coordination and failure-recovery costs

7

all participating programs must agree on the lock pathname:

  • same program / development team can establish a convention easily
  • independently written programs may use incompatible names
  • some use the data directory, others a directory such as /var/lock

8

crash can leave a stale lock file:

  • other participants then wait for an owner that no longer exists
  • timeout alone cannot prove that an owner has died; it may just be slow
  • storing owner identity can support liveness checks, with suitable care
  • sometimes recovery must be handled explicitly by the user / administrator
Tests & experiments (2 files) - 7.4.2: Creating a separate lock file
Section testadditional (07-04-02)In catalog
MakefileMake / 12 lines
PROGRAMS = file

CC = gcc
CFLAGS = -g -Wall

all: $(PROGRAMS)

$(PROGRAMS): %: %.c
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)
file.cC / 25 lines
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <err.h>

int main()
{
    int fd;

    while (1) {
        fd = open("file.t.lock", O_WRONLY|O_CREAT|O_EXCL, 0666);
        if (fd != -1) {
            close(fd);
            break;
        }
        if (errno != EEXIST)
            err(1, "some other error");
        sleep(1);
    }
    printf("opened file file.t\n");
    sleep(10);
    printf("closed file file.t\n");
    unlink("file.t.lock");
}

BSD Locks with flock

int flock(int fd, int operation);
Operation Meaning
LOCK_SH Shared lock; compatible with other shared locks
LOCK_EX Exclusive lock; incompatible with every other lock
LOCK_UN Remove the lock
LOCK_NB Add to LOCK_SH or LOCK_EX to avoid blocking

Readers normally use LOCK_SH; writers use LOCK_EX. This directly implements the basic readers-writer exclusion rule, but it does not guarantee that a writer cannot starve behind a continuous stream of readers.

Important ownership rules:

These rules can produce self-deadlock when one part of a program independently opens and locks a file already locked through another open description.

flock does not queue a waiting exclusive request ahead of new shared ones. Compile this program twice, with and without -DSHARED:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>

#ifdef SHARED
#define LOCK_MODE LOCK_SH
#define LOCK_NAME "shared"
#else
#define LOCK_MODE LOCK_EX
#define LOCK_NAME "exclusive"
#endif
#define LOCKED_SLEEP 1900000
#define UNLOCKED_SLEEP 10000

int main(int argc, char **argv)
{
    int fd, i;
    if (argc < 2) {
        fprintf(stderr, "No argument specified\n");
        return 1;
    }
    fd = open(argv[1], O_RDWR|O_CREAT, 0666);
    if (fd == -1) {
        perror(argv[1]);
        return 2;
    }
    for (i = 0; ; i++) {
        int res;
        printf("%d Getting %s lock ... ", i, LOCK_NAME);
        fflush(stdout);
        res = flock(fd, LOCK_MODE);
        printf("got it\nNow sleeping\n");
        usleep(LOCKED_SLEEP);
        printf("%d Releasing %s lock ... ", i, LOCK_NAME);
        fflush(stdout);
        res = flock(fd, LOCK_UN);
        printf("done\nNow sleeping\n");
        usleep(UNLOCKED_SLEEP);
    }
}

With two shared-lock loops started a second apart, there is always a shared holder, and the exclusive loop never gets its lock:

$ ./flock-sh lockfile > /dev/null &
$ sleep 1; ./flock-sh lockfile > /dev/null &
$ ./flock-ex lockfile
0 Getting exclusive lock ...
Detailed notes - 7.4.3: BSD locks with flock

1

flock(fd, operation) works on an already open file:

  • LOCK_SH: shared lock; compatible with other shared locks
  • LOCK_EX: exclusive lock; conflicts with shared and exclusive locks
  • LOCK_UN: release the lock

2

conflicting acquisition normally blocks until it can succeed

  • add LOCK_NB to request an immediate result instead
  • LOCK_SH|LOCK_NB or LOCK_EX|LOCK_NB
  • unlock does not need a nonblocking flag

3

shared / exclusive locks implement readers-and-writers exclusion:

  • readers may hold shared locks concurrently
  • a writer needs an exclusive lock
  • while a writer holds it, other cooperating readers and writers wait

4

exclusion alone does not guarantee fairness:

  • repeated overlapping readers can starve a writer
  • do not assume the API gives priority to a waiting writer
  • demonstration repeatedly locks, sleeps, unlocks, and sleeps again

5

build two versions of the demonstration:

  • -D SHARED selects LOCK_SH -> flock_sh
  • otherwise use LOCK_EX -> flock_ex
  • both versions operate on the pathname passed as an argument

6

demonstration timing:

  • hold lock for 1.9 seconds, release for 0.1 seconds, repeat
  • shared-lock processes can overlap
  • one reader and one writer can alternate
  • staggered readers may leave no interval in which all shared locks are free
  • -> writer waits indefinitely under the illustrated scheduling behavior

7

use an extra admission lock to prevent new readers bypassing a waiting

writer:

  • use another file as the gate
  • reader takes gate exclusively, acquires the data-file shared lock, then releases the gate
  • writer takes gate, waits for the data-file exclusive lock, and retains the gate through its operation
  • every participant must follow the same lock ordering

8

flock can convert between shared and exclusive modes

  • conversion is not guaranteed atomic
  • old lock may be released before new lock is acquired
  • another participant can intervene or the conversion can block
  • -> finish the logical critical section before changing lock type

9

BSD-style flock locks belong to the open file description:

  • fork / dup / dup2 / F_DUPFD create references to the same kernel object
  • those references therefore share the same lock
  • opening the pathname again creates an independent open description

10

consequences of open-description ownership:

  • child unlocking an inherited descriptor also removes the parent's lock
  • opening the file again and acquiring a conflicting lock can deadlock against a lock already held through the first open description
  • library code can accidentally create this second-open situation

11

locks can survive exec through inherited descriptors

  • new program may not know it inherited a locked open description
  • unrelated participants can remain blocked unexpectedly
  • descriptor lifetime and close-on-exec settings therefore matter

12

last close releases an open-description lock

  • crash closes the process's descriptors automatically
  • inherited / duplicated references elsewhere may still keep the lock alive
  • unlike a lock file, no separate stale pathname needs removal
  • network-filesystem behavior must be checked for the actual environment
BSD-style flock belongs to an open file description; traditional POSIX record locks belong to a process and file.
File-lock lifetime follows its ownership model. Open full size - Editable SVG
Examples & tests (4 files) - 7.4.3: BSD locks with flock
Book exampleBook example: flock_starve.cIn catalog
flock_starve.cC / 44 lines
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>


#ifdef SHARED
#define LOCK_MODE LOCK_SH
#define LOCK_NAME "shared"
#else
#define LOCK_MODE LOCK_EX
#define LOCK_NAME "exclusive"
#endif
#define LOCKED_SLEEP  1900000
#define UNLOCKED_SLEEP 100000


int main(int argc, char **argv)
{
    int fd, i;
    if(argc < 2) {
        fprintf(stderr, "No argument specified\n");
        return 1;
    }
    fd = open(argv[1], O_RDWR|O_CREAT, 0666);
    if(fd == -1) {
        perror(argv[1]);
        return 2;
    }
    for(i = 0; ; i++) {
        int res;
        printf("%d Getting %s lock... ", i, LOCK_NAME); fflush(stdout);
        res = flock(fd, LOCK_MODE);
        res = flock(fd, LOCK_MODE);
        printf("got it (%d)\nNow sleeping\n", res);
        usleep(LOCKED_SLEEP);
        printf("%d Releasing %s lock... ", i, LOCK_NAME); fflush(stdout);
        res = flock(fd, LOCK_UN);
        printf("done\nNow sleeping\n");
        usleep(UNLOCKED_SLEEP);
    }
}
Section testflock (07-04-03)In catalog
flock-starve-00.cC / 44 lines
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>

#ifdef SHARED
#define LOCK_MODE LOCK_SH
#define LOCK_NAME "shared"
#else
#define LOCK_MODE LOCK_EX
#define LOCK_NAME "exclusive"
#endif
#define LOCKED_SLEEP 1900000
#define UNLOCKED_SLEEP 10000

int main(int argc, char **argv)
{
    int fd, i;
    if (argc < 2) {
        fprintf(stderr, "No argument specified\n");
        return 1;
    }
    fd = open(argv[1], O_RDWR|O_CREAT, 0666);
    if (fd == -1) {
        perror(argv[1]);
        return 2;
    }
    for (i = 0; ; i++) {
        int res;
        printf("%d Getting %s lock ... ", i, LOCK_NAME);
        fflush(stdout);
        res = flock(fd, LOCK_MODE);
        printf("got it\nNow sleeping\n");
        usleep(LOCKED_SLEEP);
        printf("%d Releasing %s lock ... ", i, LOCK_NAME);
        fflush(stdout);
        res = flock(fd, LOCK_UN);
        printf("done\nNow sleeping\n");
        usleep(UNLOCKED_SLEEP);
    }
}

flock-starve-01-exclusive.cC / 43 lines
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>

#define LOCKED_SLEEP 1900000
#define UNLOCKED_SLEEP 10000

int main(int argc, char **argv)
{
    int fd1, fd2, i;
    if (argc < 3) {
        fprintf(stderr, "No argument specified\n");
        return 1;
    }
    fd1 = open(argv[1], O_RDWR|O_CREAT, 0666);
    if (fd1 == -1) {
        perror(argv[1]);
        return 2;
    }
    fd2 = open(argv[2], O_RDWR|O_CREAT, 0666);
    if (fd2 == -1) {
        perror(argv[2]);
        return 2;
    }
    for (i = 0; ; i++) {
        flock(fd2, LOCK_EX);
        printf("%d Getting %s lock ... ", i, "exclusive");
        fflush(stdout);
        flock(fd1, LOCK_EX);
        printf("got it\nNow sleeping\n");
        usleep(LOCKED_SLEEP);
        printf("%d Releasing %s lock ... ", i, "exclusive");
        fflush(stdout);
        flock(fd1, LOCK_UN);
        flock(fd2, LOCK_UN);
        printf("done\nNow sleeping\n");
        usleep(UNLOCKED_SLEEP);
    }
}

flock-starve-01-shared.cC / 43 lines
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>

#define LOCKED_SLEEP 1900000
#define UNLOCKED_SLEEP 10000

int main(int argc, char **argv)
{
    int fd1, fd2, i;
    if (argc < 3) {
        fprintf(stderr, "No argument specified\n");
        return 1;
    }
    fd1 = open(argv[1], O_RDWR|O_CREAT, 0666);
    if (fd1 == -1) {
        perror(argv[1]);
        return 2;
    }
    fd2 = open(argv[2], O_RDWR|O_CREAT, 0666);
    if (fd2 == -1) {
        perror(argv[2]);
        return 2;
    }
    for (i = 0; ; i++) {
        flock(fd2, LOCK_EX);
        flock(fd2, LOCK_UN);
        printf("%d Getting %s lock ... ", i, "shared");
        fflush(stdout);
        flock(fd1, LOCK_SH);
        printf("got it\nNow sleeping\n");
        usleep(LOCKED_SLEEP);
        printf("%d Releasing %s lock ... ", i, "shared");
        fflush(stdout);
        flock(fd1, LOCK_UN);
        printf("done\nNow sleeping\n");
        usleep(UNLOCKED_SLEEP);
    }
}

POSIX Record Locks

POSIX record locks associate a process with a byte range of a file. They are manipulated with fcntl; lockf is a simpler interface commonly implemented on top of the same facility.

int lockf(int fd, int command, int length);

lockf provides exclusive locks relative to the descriptor's current file position:

Command Meaning
F_LOCK Acquire, blocking until the range is available
F_TLOCK Try to acquire without blocking
F_ULOCK Unlock the range
F_TEST Test whether another process prevents acquisition

The descriptor must be open with write access for acquisition. Use fcntl when shared read locks, explicit offsets, or owner information are required.

struct flock lock;

lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;              /* from byte 0 through future end of file */

if (fcntl(fd, F_SETLKW, &lock) == -1)
    perror("fcntl lock");

Commands:

Command Behavior
F_SETLK Set or remove a lock; return immediately if it conflicts
F_SETLKW Set or remove a lock; wait when a requested lock conflicts
F_GETLK Report one lock that would prevent the requested operation

Relevant struct flock fields:

Field Meaning
l_type F_RDLCK, F_WRLCK, or F_UNLCK
l_whence Base position: SEEK_SET, SEEK_CUR, or SEEK_END
l_start Start relative to that base
l_len Range length; 0 means through the end of file
l_pid For F_GETLK, pid holding a reported conflicting process lock

A balance transfer must lock both account records before modifying either one. The crucial refinement is to acquire those ranges in one global order, regardless of the direction of the transfer:

/* Abridged: amount and all I/O results must be validated. */
int transfer(int fd, int from_index, int to_index, int amount)
{
    int first, second;
    account_t from, to;

    if (from_index == to_index)
        return 0;

    first = from_index < to_index ? from_index : to_index;
    second = from_index < to_index ? to_index : from_index;

    lock_record(fd, first, F_WRLCK);     /* both calls use F_SETLKW */
    lock_record(fd, second, F_WRLCK);

    from = read_account(fd, from_index); /* read only after locking */
    to = read_account(fd, to_index);
    from.balance -= amount;
    to.balance += amount;
    write_account(fd, from_index, from);
    write_account(fd, to_index, to);

    lock_record(fd, second, F_UNLCK);
    lock_record(fd, first, F_UNLCK);
    return 0;
}

A transfer from record 2 to record 7 and one from record 7 to record 2 therefore both lock 2 before 7; they cannot form an opposing lock cycle. Every cooperating reader must lock the relevant records too, or it can still observe the state between the two writes. Record locks coordinate live processes but do not make a multi-write update crash-atomic; durable transactions need a journal or a database protocol.

Overlapping ranges can merge, split, or change type as locks are added and removed.

Classic POSIX process-lock semantics contain several traps:

These rules are especially difficult in a multithreaded program, where a library call in one thread can close a descriptor and disrupt locking expected by another. Whether BSD flock locks and POSIX record locks interact also varies by system; do not mix the mechanisms unless the target platform's contract is explicit.

Detailed notes - 7.4.4: POSIX record locks

1

traditional POSIX locks can cover part of a file

  • flock covers the whole file
  • record locks describe a byte range

2

traditional POSIX lock ownership is process + file:

  • different descriptors for the same file access that process's locks
  • this includes descriptors obtained by separate open calls
  • fork does not give the child ownership of the parent's record locks
  • distinct from the open-description ownership used by flock

3

interfaces:

  • fcntl with F_SETLK, F_SETLKW, F_GETLK
  • lockf(fd, cmd, len), commonly implemented through fcntl
  • fcntl supports read and write locks
  • lockf provides exclusive locking only

4

lockf parameters:

  • fd: file opened with write access
  • F_LOCK: acquire, waiting if necessary
  • F_TLOCK: try to acquire without waiting
  • F_UNLOCK: release
  • F_TEST: query whether a conflicting lock prevents acquisition
  • len: range length from the current file position
  • negative length selects the range preceding that position

5

lockf result:

  • 0: success
  • -1: failure
  • with F_TEST, success means no conflicting lock was found at that moment
  • a successful test does not reserve the range

6

fcntl record-lock commands receive a struct flock pointer:

  • fcntl(fd, F_SETLKW, &lock)
  • struct flock is a data type, separate from the flock function

7

struct flock fields:

  • l_type: F_RDLCK, F_WRLCK, or F_UNLCK
  • l_whence: SEEK_SET, SEEK_CUR, or SEEK_END
  • l_start: starting offset relative to l_whence
  • l_len: range length; negative selects preceding bytes
  • l_len = 0: extend from the start through EOF, including later growth
  • l_pid: owner information returned by F_GETLK

8

F_GETLK queries a proposed lock:

  • first describe the desired range and lock type
  • no conflict -> l_type becomes F_UNLCK
  • conflict -> structure describes a conflicting lock and its owner's pid
  • query does not acquire the lock

9

F_SETLK and F_SETLKW acquire, change, or release a lock:

  • fill l_type, l_whence, l_start, and l_len
  • F_SETLK returns immediately if another lock prevents acquisition
  • F_SETLKW waits for the conflict to clear; W means wait
  • handle errors and interruption in either case

10

partial unlock can split an existing range:

  • lock 1000 bytes starting at 500 -> [500, 1500)
  • unlock 100 bytes starting at 700 -> [700, 800)
  • remaining locks: [500, 700) and [800, 1500)
  • overlapping changes can also merge ranges or alter their lock types

11

POSIX record locking can be supported by network filesystems

  • depends on protocol and kernel support
  • do not infer universal guarantees from the name of a locking API alone

Transfers in either direction acquire account-record locks in
ascending record order,
preventing opposite lock orders from forming a deadlock.

Tests & experiments (6 files) - 7.4.4: POSIX record locks
Section testlockf-fcntl (07-04-04)In catalog
MakefileMake / 21 lines
SRCMODULES = tools.c
OBJMODULES = $(SRCMODULES:.c=.o)

PROGRAMS = create read modify

CC = gcc
CFLAGS = -g -Wall

all: $(PROGRAMS)

%.o: %.c %.h
    $(CC) -c $< -o $@ $(CFLAGS)

$(PROGRAMS): %: %.c $(OBJMODULES)
    $(CC) $^ -o $@ $(CFLAGS)

clean:
    rm -f *.o $(PROGRAMS)

ctags:
    ctags *.c *.h
create.cC / 22 lines
#include <unistd.h>

#include "tools.h"

int main(int argc, char **argv)
{
    int fd;
    int data[] = {
        1, 100,
        2, 100,
        3, 100,
        4, 100,
        5, 100,
    };

    check_arguments(argc, argv[0]);
    fd = open_file(argv[1], 'w');
    write(fd, data, sizeof(data));

    close(fd);
    return 0;
}
modify.cC / 47 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/file.h>

#include "tools.h"

int main(int argc, char **argv)
{
    int fd, size, sleep_time, first, second, diff;
    int from[2], to[2];
    struct flock s1, s2;

    if (argc < 6) {
        fprintf(stderr, "usage %s <file name> <time interval> "
                "<diff> <first data> <second data>\n", argv[0]);
        exit(1);
    }
    fd = open_file(argv[1], 'm');
    size = lseek(fd, 0, SEEK_END);
    lseek(fd, 0, SEEK_SET);

    sleep_time = str2long(argv[2]);
    diff = str2long(argv[3]);
    first = str2long(argv[4]) - 1;
    second = str2long(argv[5]) - 1;

    lock(fd, first * sizeof(from), sizeof(from), &s1);
    lock(fd, second * sizeof(from), sizeof(from), &s2);

    read_data(fd, from, first);
    read_data(fd, to, second);

    sleep(sleep_time);

    modify_data(fd, from, first, -diff);
    modify_data(fd, to, second, diff);

    s1.l_type = F_UNLCK;
    fcntl(fd, F_SETLKW, &s1);

    s2.l_type = F_UNLCK;
    fcntl(fd, F_SETLKW, &s2);

    close(fd);
    return 0;
}
read.cC / 30 lines
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <err.h>

#include "tools.h"

enum {
    data_size = 10
};

int main(int argc, char **argv)
{
    int fd, i;
    int data[data_size];

    check_arguments(argc, argv[0]);

    fd = open_file(argv[1], 'r');

    read(fd, data, sizeof(data));
    for (i = 0; i < data_size; i++) {
        printf("%d ", data[i]);
        if (i % 2 == 1)
            printf("\n");
    }

    close(fd);
    return 0;
}
tools.cC / 96 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <err.h>
#include <string.h>

#include "tools.h"

void *xmalloc(int size)
{
    void *p;

    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

long str2long(const char *str)
{
    int n;
    char *endptr;

    n = strtol(str, &endptr, 10);
    if (errno == ERANGE || !*str || *endptr)
        err(1, str);

    return n;
}

void check_arguments(int argc, const char *program_name)
{
    if (argc < 2) {
        fprintf(stderr, "usage %s <file name>\n", program_name);
        exit(1);
    }
}

int open_file(const char *file_path, int mode)
{
    int fd;

    switch (mode) {
        case 'w':
            fd = open(file_path, O_WRONLY|O_CREAT|O_TRUNC, 0666);
            break;
        case 'e':
            fd = open(file_path, O_WRONLY|O_CREAT|O_EXCL, 0666);
            break;
        case 'm':
            fd = open(file_path, O_RDWR, 0666);
            break;
        case 'r':
            fd = open(file_path, O_RDONLY);
            break;
    }
    if (fd == -1)
        err(1, file_path);

    return fd;
}

void read_data(int fd, int *data, int start)
{
    int rc;

    lseek(fd, start * sizeof(data), SEEK_SET);
    rc = read(fd, data, sizeof(data));
    if (rc != sizeof(data)) {
        fprintf(stderr, "wrong data read\n");
        exit(1);
    }
}

void modify_data(int fd, int *data, int start, int diff)
{
    int original = data[1];

    lseek(fd, start * sizeof(data) + sizeof(data[0]), SEEK_SET);
    data[1] += diff;
    write(fd, &data[1], sizeof(data[1]));
    printf("%d: %d -> %d\n", data[0], original, data[1]);
}

void lock(int fd, int start, int len, struct flock *s)
{
    s->l_type = F_WRLCK;
    s->l_whence = SEEK_SET;
    s->l_start = start;
    s->l_len = len;
    fcntl(fd, F_SETLKW, s);
}

tools.hC / 17 lines
#ifndef TOOLS_H
#define TOOLS_H

#include <fcntl.h>

void *xmalloc(int size);
long str2long(const char *str);

void check_arguments(int argc, const char *program_name);
int open_file(const char *file_path, int mode);

void read_data(int fd, int *data, int start);
void modify_data(int fd, int *data, int start, int diff);

void lock(int fd, int start, int len, struct flock *s);

#endif

Choosing a File-Locking Mechanism

Question Why it matters
Do all programs cooperate? Advisory locks cannot constrain an unaware participant
Is the file local or remote? Network filesystems vary in atomicity and lock propagation
Is a whole-file lock sufficient? If yes, flock or a lock file is easier to audit
Are byte-range locks truly required? fcntl adds power and substantially more semantic complexity
What happens after a crash? Kernel locks vanish; a separate lock file can remain stale
Can libraries reopen or close the file? This can self-deadlock flock or erase classic POSIX locks
Can readers continuously starve writers? Shared/exclusive compatibility does not itself guarantee fairness

Avoid shared writable files when ownership can be divided cleanly. When sharing is inherent to the problem, keep the protocol small, document it as part of the file format, and test it on the actual filesystems where it will run.

Detailed notes - 7.4.5: File-locking pitfalls

1

closing any descriptor for a file releases that process's traditional POSIX

record locks on the file

  • even a descriptor obtained by an independent open
  • library may open and close the file, unexpectedly dropping application locks
  • another subsystem can also change the process's lock type on an overlap
  • all threads in the process share this ownership problem

2

read permission can allow interference with cooperating writers:

  • a shared lock can hold up an exclusive writer indefinitely
  • with local BSD-style flock, even an exclusive lock can be requested through a read-only descriptor
  • ability to acquire a lock is different from permission to modify data

3

interaction between locking APIs varies:

  • lockf commonly uses the same locks as fcntl
  • native flock and traditional fcntl locks can be independent
  • another system may connect them or implement flock through fcntl
  • filesystem and protocol behavior can change these relationships
  • -> cooperating programs must agree on a compatible mechanism

4

author's conclusion: avoid unnecessary shared file access

  • where sharing is required, account for ownership, descriptor lifetime, fairness, failure recovery, and portability
  • one successful experiment does not establish those guarantees

Main Lessons

Previous: Networks and Protocols Reading map Next: Inside the Kernel

Comments

Leave a comment Sign in All comments