Protect Shared Data with pthread_mutex_lock
Guard a shared linked-list stack in C with pthread_mutex_lock and pthread_mutex_unlock on glibc 2.41, check return codes, and avoid leaks from missed unlocks.

Wrapping one counter in a lock is easy. Real programs share structures: a list of jobs, a cache, a table of connections. The rule is the same, but the habits are different. The lock must cover every access, including reads. It must be released on every path out of the function, including error paths. And it must live next to the data it guards so nobody has to guess which lock goes with which variable. This post builds a small thread-safe stack of integers in C with POSIX threads on Linux, glibc 2.41 and GCC 14, and shows the idioms that keep a mutex-protected structure correct as it grows. It follows the basics in the earlier post on race conditions and mutexes in this cluster.
Put the mutex inside the structure
The most useful habit is to declare the mutex in the same struct as the data. Then the data and its guard travel together, and a function that takes a pointer to the structure has what it needs to lock.
#ifndef STACK_H
#define STACK_H
#include <pthread.h>
#include <stddef.h>
struct node {
int value;
struct node *next;
};
struct stack {
pthread_mutex_t lock;
struct node *top;
size_t size;
};
int stack_init(struct stack *s);
void stack_destroy(struct stack *s);
int stack_push(struct stack *s, int value);
int stack_pop(struct stack *s, int *out);
size_t stack_size(struct stack *s);
#endifA comment in a real header should say which fields the lock protects. Here the rule is simple: lock guards top and size, and nothing in the structure may be touched without holding it.
Initialize and destroy the mutex
A global mutex can use PTHREAD_MUTEX_INITIALIZER. A mutex inside a heap or stack object must be initialized with pthread_mutex_init, which returns zero on success and an error number on failure. It does not set errno. This is a common POSIX convention: the pthread_* functions return the error code directly.
#include "stack.h"
#include <stdlib.h>
int stack_init(struct stack *s) {
s->top = NULL;
s->size = 0;
return pthread_mutex_init(&s->lock, NULL);
}
void stack_destroy(struct stack *s) {
struct node *n = s->top;
while (n) {
struct node *next = n->next;
free(n);
n = next;
}
pthread_mutex_destroy(&s->lock);
}stack_destroy does not lock. That is deliberate and it is also a rule: you may destroy a mutex only when no thread holds it and none can still reach it. POSIX says destroying a locked mutex is undefined behavior. Join every worker thread before you call stack_destroy.
Lock around every access
Now the operations. Each one takes the lock, touches the fields, and drops the lock before returning.
int stack_push(struct stack *s, int value) {
struct node *n = malloc(sizeof *n);
if (!n)
return -1;
n->value = value;
pthread_mutex_lock(&s->lock);
n->next = s->top;
s->top = n;
s->size++;
pthread_mutex_unlock(&s->lock);
return 0;
}
int stack_pop(struct stack *s, int *out) {
pthread_mutex_lock(&s->lock);
struct node *n = s->top;
if (!n) {
pthread_mutex_unlock(&s->lock);
return -1;
}
s->top = n->next;
s->size--;
pthread_mutex_unlock(&s->lock);
*out = n->value;
free(n);
return 0;
}
size_t stack_size(struct stack *s) {
pthread_mutex_lock(&s->lock);
size_t n = s->size;
pthread_mutex_unlock(&s->lock);
return n;
}Look at three details. First, malloc happens before the lock in stack_push. Allocation can be slow, and nothing about it needs exclusion, so do it outside the critical section. Second, stack_pop has an early return, and that path unlocks before it returns. Forgetting this unlock is the classic mutex bug: the next caller blocks forever, and the program hangs rather than crashes. Third, stack_size locks even though it only reads. A read while another thread is writing size is a data race, so reads need the lock too.
After stack_pop removes the node under the lock, the node belongs to the caller alone. No other thread can reach it, so reading n->value and calling free happen outside the lock. Shrinking the critical section like this is safe only because the node is already unlinked.
Drive it from threads
#include "stack.h"
#include <stdio.h>
#define PER_THREAD 100000
static struct stack st;
static void *pusher(void *arg) {
int base = *(int *)arg;
for (int i = 0; i < PER_THREAD; i++)
stack_push(&st, base + i);
return NULL;
}
int main(void) {
pthread_t t[4];
int base[4] = {0, 1000000, 2000000, 3000000};
stack_init(&st);
for (int i = 0; i < 4; i++)
pthread_create(&t[i], NULL, pusher, &base[i]);
for (int i = 0; i < 4; i++)
pthread_join(t[i], NULL);
printf("size = %zu\n", stack_size(&st));
int v;
int popped = 0;
while (stack_pop(&st, &v) == 0)
popped++;
printf("popped = %d\n", popped);
stack_destroy(&st);
return 0;
}Build with gcc -O2 -pthread main.c stack.c -o stack. Four threads push 100,000 values each:
size = 400000
popped = 400000The order of values in the stack varies, but the count never does, because every push updates top and size under the same lock. Remove the lock calls from stack_push and the size will come up short and the list may lose nodes, or worse, corrupt the next pointers and crash in free.
Check the return values
Our examples skipped checks on pthread_mutex_lock to keep the shape clear. For a default mutex, pthread_mutex_lock can return EINVAL if the mutex is not initialized, or EDEADLK on error-checking mutexes when the thread already owns it. In production code that sits behind a project-wide wrapper, or an assert. The pattern is:
#include <assert.h>
#include <pthread.h>
void locked_increment(pthread_mutex_t *m, long *value) {
int rc = pthread_mutex_lock(m);
assert(rc == 0);
(*value)++;
rc = pthread_mutex_unlock(m);
assert(rc == 0);
}Compiled with NDEBUG the asserts vanish, and rc becomes unused, so many projects use a macro that always evaluates the call. The POSIX manual for pthread_mutex_lock lists the possible error values.
Three mistakes that hang or corrupt
The first is a missing unlock on an error or early-return path. Every return between lock and unlock is a bug. In C there is no destructor to save you, so structure functions with a single exit, or use the goto out idiom with one unlock at the label.
The second is locking some accesses and not others. If stack_size skipped the lock because it only reads, the program would pass most tests, and ThreadSanitizer would flag it. Every thread that touches the data takes the lock, readers included.
The third is holding a lock across a slow call. If stack_push took the lock before malloc and held it across a file write, every other thread would queue behind a disk. Keep the section to the memory updates and nothing else.
When this is the wrong shape
A coarse lock around a whole structure is the right starting point and often the right ending point. If profiling shows the mutex is the bottleneck, the next steps are splitting it into several locks over parts of the data, a read-write lock when reads dominate, or a lock-free design. Do those only when you have a measurement. Fine-grained locking is the main source of deadlocks, so earn it.
Testing a locked structure
A locked structure can pass every functional test and still be wrong, because the failures are timing-dependent. Two habits help. First, write a stress test that looks like main.c above: many threads, many operations, and an invariant you can check at the end, such as the count of pushes equaling the count of pops. An invariant that holds across a hundred thousand operations per thread is far more convincing than a unit test that pushes three values.
Second, run that stress test under ThreadSanitizer. Build with gcc -g -O1 -fsanitize=thread -pthread main.c stack.c -o stack_tsan. The tool reports a data race the moment two unordered accesses touch the same address, even if the final numbers look right. If you delete the lock from stack_size, the report names the line in stack_size and the line in stack_push that wrote the field, which points directly at the missing guard. The GCC manual documents -fsanitize=thread among its instrumentation options.
Valgrind's Helgrind tool is the alternative when you cannot recompile. It also reports lock-order problems and misuse of the POSIX API, such as unlocking a mutex held by another thread, which ThreadSanitizer also catches. Neither tool proves the absence of a bug, since they only see the interleavings that happen during the run, so keep the stress test running for long enough to explore many of them.


