©Code by Samnoon
Blog
← All posts

c

POSIX threads in comms software: locks, waits and debugging hangs

Bounded queues, condition variables done properly, priority inversion, and the gdb, helgrind and TSan commands for when it all locks up.

6 min read

Comms software tends to look the same from the inside. One thread reads bytes off a device or a socket. A few threads do something with them. Another thread writes bytes back out. Queues connect them all. It's a sensible design, and it fails in a small number of very predictable ways.

This post is about those ways: the queue in the middle of everything, condition variables, lock contention, priority inversion, and what to do when the whole process simply stops.

A bounded queue

Every hand-off between threads goes through something like this:

queue.c
#include <pthread.h>
#include <stdbool.h>
#include <stddef.h>
 
#define QUEUE_CAP 256
 
typedef struct {
    pthread_mutex_t mu;
    pthread_cond_t  not_empty;
    pthread_cond_t  not_full;
    void           *items[QUEUE_CAP];
    size_t          head, tail, count;
    bool            closed;
} queue_t;
 
void queue_init(queue_t *q)
{
    pthread_mutex_init(&q->mu, NULL);
    pthread_cond_init(&q->not_empty, NULL);
    pthread_cond_init(&q->not_full, NULL);
    q->head = q->tail = q->count = 0;
    q->closed = false;
}
 
int queue_push(queue_t *q, void *item)
{
    pthread_mutex_lock(&q->mu);
    while (q->count == QUEUE_CAP && !q->closed)
        pthread_cond_wait(&q->not_full, &q->mu);
 
    if (q->closed) {
        pthread_mutex_unlock(&q->mu);
        return -1;
    }
 
    q->items[q->tail] = item;
    q->tail = (q->tail + 1) % QUEUE_CAP;
    q->count++;
    pthread_cond_signal(&q->not_empty);
    pthread_mutex_unlock(&q->mu);
    return 0;
}
 
/* Returns NULL once the queue is closed and empty */
void *queue_pop(queue_t *q)
{
    pthread_mutex_lock(&q->mu);
    while (q->count == 0 && !q->closed)
        pthread_cond_wait(&q->not_empty, &q->mu);
 
    void *item = NULL;
    if (q->count > 0) {
        item = q->items[q->head];
        q->head = (q->head + 1) % QUEUE_CAP;
        q->count--;
        pthread_cond_signal(&q->not_full);
    }
    pthread_mutex_unlock(&q->mu);
    return item;
}
 
void queue_close(queue_t *q)
{
    pthread_mutex_lock(&q->mu);
    q->closed = true;
    pthread_cond_broadcast(&q->not_empty);
    pthread_cond_broadcast(&q->not_full);
    pthread_mutex_unlock(&q->mu);
}

It's bounded on purpose. An unbounded queue hides overload: the producer never slows down, memory keeps growing, and you find out when the OOM killer does. A bounded queue pushes back. When the consumer can't keep up, the producer blocks, and the slowdown shows up where it's caused, which is also where you can measure it.

queue_close is what makes a clean shutdown possible. It wakes every waiting thread. Pushers give up, poppers drain what's left and then get NULL. Shutdown is the part people skip when they write a queue, and then they reach for pthread_cancel, which is almost never the right answer in C code that holds locks.

Three rules for condition variables

First, always wait in a loop that re-checks the condition. pthread_cond_wait is allowed to return when nothing has changed (a spurious wakeup), and even after a real signal another thread may have taken the item before you got the lock back. Using if instead of while works in testing and fails under load.

Second, only change the condition while holding the mutex. If a producer bumps count without the lock, a consumer can see count == 0, decide to wait, and miss a signal sent in the gap between its check and its wait. That's a lost wakeup, and it looks like a thread that goes to sleep forever for no reason.

Third, broadcast when more than one waiter needs to act. signal wakes one waiter, which is right for "one item was added". "The queue is closing" concerns every waiter, so it's a broadcast.

Contention

A design with one big mutex around the shared state works fine until it has to scale. Then every thread spends its time waiting for the others. CPU usage looks low, and throughput stays flat no matter how many threads you add.

perf finds it quickly. With glibc, a thread blocked on a contended mutex ends up in __lll_lock_wait and then in the kernel's futex code:

perf top -p "$(pidof commsd)"

If __lll_lock_wait or the futex functions are near the top, you have contention. perf record -g -p <pid> followed by perf report shows which call paths were fighting over the lock.

The fixes are mostly boring. Hold locks for less time: copy what you need while holding the lock, then do the work after releasing it. Split one lock into several if the data really is independent. And keep I/O out of critical sections entirely. A write() to a slow device while holding a lock every other thread needs is a classic way to turn a fast system into a slow one.

Priority inversion

If you use real-time scheduling (SCHED_FIFO) for latency-sensitive threads, there's one more trap. A high-priority thread waits on a mutex held by a low-priority thread. A medium-priority thread that needs neither of them preempts the low-priority one and keeps running. The high-priority thread is now stuck behind the medium one, for as long as it likes.

That's priority inversion, and it famously caused repeated resets on NASA's Mars Pathfinder lander in 1997. The fix there is available to you too: priority inheritance, where a thread holding a mutex temporarily takes on the priority of the highest-priority thread waiting for it.

pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT);
pthread_mutex_init(&q->mu, &attr);
pthread_mutexattr_destroy(&attr);

If you don't use real-time priorities, you can skip this section. If you do, every mutex shared between threads of different priorities should be set up this way.

Name your threads

pthread_setname_np(pthread_self(), "rx-reader");

Names can be at most 15 characters. They show up in top -H, in ps -L -o pid,lwp,comm -p <pid>, and in gdb's info threads. When you're reading a stack dump of twelve threads in the middle of an incident, "rx-reader" is a lot more helpful than an anonymous thread ID.

When the process hangs

A hang in a threaded program is usually a deadlock (two threads each waiting for a lock the other holds) or a lost wakeup (a thread waiting on a condition nobody's ever going to signal). The stacks tell you which. Grab them before you restart anything:

gdb -p "$(pidof commsd)" -batch -ex 'thread apply all bt' > "hang-$(date +%s).txt"

That attaches, prints every thread's backtrace and detaches again. The process pauses for a moment; it isn't killed. Then read through the file for threads sitting in __lll_lock_wait (waiting for a mutex) or pthread_cond_wait (waiting on a condition), and work out what each one is waiting for and who should have released it. If gdb isn't installed on the box, eu-stack -p <pid> from elfutils does the same job.

Two habits make deadlocks much rarer to begin with. Always take locks in the same global order, and write that order down next to the lock definitions. And never call code you don't control, like a callback or a logging hook, while holding a lock.

Catching races before production does

There are two good tools, with different trade-offs.

Helgrind and DRD (valgrind --tool=helgrind ./commsd) need no recompiling and find both lock-ordering problems and data races. They're very slow, though, so they're for targeted runs rather than your whole test suite.

ThreadSanitizer (-fsanitize=thread in GCC or Clang) needs a rebuild, but it's much faster, typically somewhere between 5 and 15 times slower than a normal build, and its reports point at the exact pair of accesses that raced. It can't share a build with AddressSanitizer, so most projects run it as a separate CI job.

A race that TSan finds in CI costs you an afternoon. The same race found in the field costs a great deal more, most of it spent failing to reproduce it.

References

#c #linux #concurrency