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
flock, POSIX record
locks, ownership rules, failure modes, and portability limitsparallel programming: divide work into subtasks that can execute concurrently
multithreading = programming with multiple threads of execution
thread, flow, and stream have overlapping Russian translations
book uses "thread" for one execution thread
multicore processors made parallel programming widely available
Amdahl's law: the serial part limits total speedup
book highlights numerical simulation and video processing as parallel workloads
interactive compression / decompression example:
creating threads does not itself create useful parallel work
several independent event sources complicate sequential control flow
event-driven design: wait for an available event, identify its source, then handle it
one thread per event source can hide session state in thread execution state
shared data: data accessible to several independently executing participants
shared-data access requires deliberate coordination
understanding the need for synchronization is part of writing threaded programs
author's experience: programmers may use mutexes without being able to justify them
concurrency bugs may require rare execution interleavings
Edward Lee's cited argument: threads introduce many possible execution orderings
shared-data problems matter even when choosing not to use threads
independent programs can share data without belonging to one parallel application
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.
If a fraction of a computation remains sequential and the remaining fraction is divided perfectly among processors, the best possible speedup is
The sequential fraction places a hard ceiling on speedup:
| Sequential fraction | Processors | Ideal speedup | Absolute ceiling |
|---|---|---|---|
| 10 | |||
| 100 | |||
| 21 | |||
| 361 |
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.
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:
; 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.
two processes increment a shared integer initially equal to 5
some processors offer atomic memory arithmetic, e.g. suitable x86 LOCK operations
first process loads 5, then is interrupted
first process resumes with its old register value 5
bank example: account balances 301 = $1000, 515 = $1500, 768 = $2000
transfer B reads balances, then pauses while A completes
read-only summation can also race with transfers
common cause: computation uses input that became stale during the operation
data becoming old is not automatically an error
load shared_count -> add one -> store shared_count
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
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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
}
#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
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
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
#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;
}
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:
| 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.
serializing entire process lifetimes is usually too restrictive
keep related input consistent for the duration of a shared-data operation
critical section: logically connected manipulations of particular shared data
"critical section" can mean either:
critical sections are defined relative to particular data
two critical sections conflict when:
mutual exclusion: conflicting critical sections cannot execute simultaneously
participants follow synchronization rules voluntarily
requirements for the book's exclusion mechanisms:
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.
this subsection studies shared-variable algorithms with busy waiting
naive lock variable s: 1 = free, 0 = occupied
race: first process sees s == 1, then pauses before storing 0
testing availability and claiming the resource must form one atomic action
disabling hardware interrupts is not a general user-space solution
busy waiting with interrupts disabled can freeze a uniprocessor system
ordinary user processes cannot disable interrupts
strict alternation: shared turn chooses process 0 or process 1
alternation prevents simultaneous entry but can prevent useful progress
Peterson's algorithm: two participants, numbered 0 and 1
participant i enters by:
Peterson supplies enter_section and leave_section procedures
#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;
}
#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;
}
#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;
}
#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;
}
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.
busy waiting repeatedly polls shared state while doing no useful work
mutex: initially unlocked object with lock and unlock operations
mutex ownership rule: only the participant that locked it may unlock it
absence of an ownership check does not permit another thread to unlock a mutex
acquisition must be atomic with respect to other participants
replace the naive lock variable with a real mutex
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 |
/* 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.
kernel manages blocking and wakeup of scheduled processes / threads
entering the kernel for every acquisition and release can be expensive
atomic CPU operations allow an uncontended user-space fast path
example representation: integer mutex, 1 = free, 0 = locked
simple assembly spinlock repeats exchange until the old value is 1
practical blocking implementations track contended locks and waiters
Linux futex supports waiting and waking around a shared user-space word
uncontended mutex operations often stay entirely in user space
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
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
#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
#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;
}
#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);
}
#ifndef FUTEX_H
#define FUTEX_H
void futex_wait(int *futex, int expected);
void futex_wake(int *futex, int num);
#endif
/* 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);
}
#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;
}
#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);
}
}
#ifndef MUTEX_H
#define MUTEX_H
void lock(int *val);
void unlock(int *val);
#endif
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
can count
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
semaphore operations resemble mutex operations at first glance
mutex protects ownership of a shared resource
counting semaphore holds a nonnegative integer
binary semaphore uses values 0 and 1
counting semaphore can represent several available resources
historical attribution: semaphore abstraction is associated with Edsger Dijkstra
do not use mutex ownership violations as a substitute for semaphore signaling
semaphore as resource counter:
some implementations provide additional operations:
System V semaphore arrays support compound atomic operations
pipe illustration: one queued byte represents one available permit
examples use abstract C-like pseudocode
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 |
Number of items producers may still insert | |
full_slots |
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.
#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.
producers generate data for later processing
consumers process the data prepared by producers
bounded shared buffer holds N fixed-size items
two resource shortages must block useful work:
repeatedly locking, checking, unlocking, and retrying is busy waiting
counting semaphores prevent entry until a needed resource is available
put_data / get_data perform only buffer manipulation
producer:
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
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
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
#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
#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);
}
#ifndef FUTEX_H
#define FUTEX_H
void futex_wait(int *futex, int expected);
void futex_wake(int *futex, int num);
#endif
#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;
}
#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);
}
}
#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);
}
#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
#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;
}
#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;
}
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:
#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.
deadlock: participants wait for resources held by one another
English technical term: deadlock
five philosophers share five forks around a table
if all five acquire their left fork, nobody can acquire the right fork
two processes and two mutexes suffice for deadlock
deadlock also occurs without explicit mutexes
child must finish writing ls output before it exits
pipe buffer has finite capacity
dependency cycle: parent waits for exit; child waits for parent's read
naive philosopher implementation uses five fork mutexes
limit the number attempting acquisition with a counting semaphore
at most four philosophers may compete under this semaphore solution
resource ordering: always acquire lower-numbered fork before higher-numbered fork
ordering can be partial rather than a complete numbering
resource ordering has practical tradeoffs
steward mutex serializes acquisition of fork pairs
starvation: participant repeatedly fails to obtain the resources it needs
state-based solution: thinking, hungry, or eating for each philosopher
one state_mutex protects the state array; separate fork mutexes are unnecessary
state-based solution prevents deadlock but does not guarantee no starvation
Chandy-Misra solution uses ownership transfer and messages
hungry philosopher requests each missing fork from its holder
on receiving a fork request:
clean/dirty distinction prevents neighbors endlessly reclaiming a newly received fork
book explains why five philosophers make a useful teaching example
one philosopher: no competition
three philosophers: again only one can eat at a time
four philosophers can eat as two fixed pairs of opposite seats
five participants remove these particular one-resource / fixed-pair simplifications
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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, ¤t_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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
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
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
#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
#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);
}
#ifndef FUTEX_H
#define FUTEX_H
void futex_wait(int *futex, int expected);
void futex_wake(int *futex, int num);
#endif
#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;
}
#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);
}
}
#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);
}
#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
#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;
}
#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;
}
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
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
#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
#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);
}
#ifndef FUTEX_H
#define FUTEX_H
void futex_wait(int *futex, int expected);
void futex_wake(int *futex, int num);
#endif
#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;
}
#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);
}
}
#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);
}
#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
#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;
}
#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;
}
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.
graph described in the book has process nodes and resource nodes
examples distinguish a graph without a wait cycle from:
reduce the graph by repeatedly removing edges:
transactions allow recovery when avoiding every deadlock is impractical
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:
reader_count, initially 0, protected by an
unlocked reader_count_mutexdata_access, initially
1, acquired by the first reader and released by the last
readervoid 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.
allow several readers at once, but make writers exclusive
shared rc counts active readers
writer: down(db_access); modify data; up(db_access)
reader entry:
continuous overlapping readers can keep rc above zero indefinitely
add barrier mutex to stop admitting new readers once a writer owns it
writer waits for admitted readers to finish, writes, then releases db_access and barrier
#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 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.
#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.
one barber, one work chair, and N waiting-room chairs
barber finishes one client, then takes another waiting client
arriving client wakes an idle barber
checking a condition and acting on it are separate operations
lost coordination example:
common solution needs seat count, protected by a mutex, plus customer/barber semaphores
shared state:
barber loop:
inviting a client and updating free-seat count are coordinated under seats_mutex
client:
this client also announces itself through customers inside seats_mutex
fuller model assumes a passive client during the haircut
assume BARBER_WORK / CUSTOMER_WORK handle their own rendezvous correctly
reserving a seat first and posting customers afterward needs separate analysis
literal story details are not all represented by the semaphore model
author's revision history illustrates why synchronization explanations need precision
The core protocol is:
#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;
}
#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;
}
#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 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
practical thread examples let us test shared-data synchronization concepts
understand thread programming even when choosing another design
threads belong to one process and share its virtual address space
each thread's stack is still memory in the common address space
#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;
}
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:
#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.
POSIX standardized thread interfaces under the name POSIX Threads / pthreads
thread entry function has form void *entry(void *arg)
pthread_create(&thread, attributes, entry, argument): start a thread
thread finishes by returning from its entry function or calling pthread_exit(result)
pthread_join(thread, &result): wait for a joinable thread to finish
joinable thread retains termination information until joined
pthread_self(): obtain caller's pthread_t
pthread_cancel(thread): request cancellation
#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;
}
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.
POSIX mutex and semaphore interfaces use different naming conventions
pthread_mutex_t represents a mutex
mutex functions take pthread_mutex_t*:
sem_t represents a POSIX semaphore
process-shared semaphore support depends on implementation
sem_init(&sem, pshared, value): initialize an unnamed semaphore
sem_post(&sem): add one permit, waking a waiter if needed
sem_getvalue(&sem, &value): obtain an observed semaphore value
sem_destroy(&sem): end semaphore lifetime
#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);
}
#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;
}
#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 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.
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.
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.
#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.
demonstration tests shared-data correctness rather than solving a useful application task
main creates an integer array, initially all zeros
compile the same example with synchronization enabled or disabled
thread startup introduces a second shared-data problem
workers need independent pseudo-random generator state
book uses rand_r(&seed) with an unsigned int seed private to each worker
main obtains time(NULL) once, then increments the seed for each new worker
startup information includes seed, shared array, and its mutex
one void* can point to a structure containing all startup data
startup race: worker reads the structure while main prepares the next worker
one structure per worker is a possible alternative
example instead uses a copy-and-acknowledge handshake
startup semaphore initially 0
example constants:
thread_start_data also receives sem_t *data_sem
worker entry:
main's local variables hold the shared array and startup structure
initialize startup structure once:
worker creation loop:
printing loop must observe one consistent state
main also ends with an unreachable return 0 after its infinite loop
book supplies the complete example as balance.c
sample output shows zero totals with protection and drifting totals without it
older producer-consumer demonstration was corrected after errors were found
conclusion: hidden shared state can appear inside called library functions
author favors threads only when independent computation gives a measured multicore benefit
#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;
}
#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;
}
#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;
}
#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;
}
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.
shared disk data can be unavoidable even when shared memory is avoided
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.
file lock: a way to tell other processes that a file is in use
the book distinguishes the English word lock from blocking
the author uses the Russian term meaning acquisition / capture for a lock
ordinary Unix file locks are advisory:
all participants must cooperate:
mandatory locking would enforce restrictions on ordinary I/O too
three approaches considered:
network filesystems add another layer of semantics:
author suggests configurable support for several locking mechanisms
PROGRAMS = readv
CC = gcc
CFLAGS = -g -Wall
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
#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;
}
O_EXCLA 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.
lock-file protocol for foobar.dat:
analogy with a mutex:
alternative when exclusive creation cannot be relied on:
network errors can make the outcome of link ambiguous:
release by removing the agreed hard-link pathname
advantages of this approach:
all participating programs must agree on the lock pathname:
crash can leave a stale lock file:
PROGRAMS = file
CC = gcc
CFLAGS = -g -Wall
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
#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");
}
flockint 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:
dup and inherited across
fork refer to that same description and therefore the same
lockexec normally preserves the lock when it preserves
the descriptorThese 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 ...
flock(fd, operation) works on an already open file:
conflicting acquisition normally blocks until it can succeed
shared / exclusive locks implement readers-and-writers exclusion:
exclusion alone does not guarantee fairness:
build two versions of the demonstration:
demonstration timing:
use an extra admission lock to prevent new readers bypassing a waiting
writer:
flock can convert between shared and exclusive modes
BSD-style flock locks belong to the open file description:
consequences of open-description ownership:
locks can survive exec through inherited descriptors
last close releases an open-description lock
#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);
}
}
#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);
}
}
#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);
}
}
#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 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:
forkThese 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.
traditional POSIX locks can cover part of a file
traditional POSIX lock ownership is process + file:
interfaces:
lockf parameters:
lockf result:
fcntl record-lock commands receive a struct flock pointer:
struct flock fields:
F_GETLK queries a proposed lock:
F_SETLK and F_SETLKW acquire, change, or release a lock:
partial unlock can split an existing range:
POSIX record locking can be supported by network filesystems
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
#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;
}
#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;
}
#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;
}
#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);
}
#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
| 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.
closing any descriptor for a file releases that process's traditional POSIX
record locks on the file
read permission can allow interference with cooperating writers:
interaction between locking APIs varies:
author's conclusion: avoid unnecessary shared file access
Previous: Networks and Protocols Reading map Next: Inside the Kernel
Comments