Linux System Programming · intermediate · ~10 min
Recognise the bugs that bite every C programmer learning pthreads.
-pthread. Linker error or worse — code compiles but pthread_mutex calls become no-ops on some platforms.&i from a loop. All threads see the post-loop value. Pass by value or by heap pointer.counter++ is not atomic. Use a mutex or _Atomic long.signal() in a threaded program. Use sigaction() and consider blocking signals on worker threads with pthread_sigmask.if instead of while around cond_wait. Spurious wakeups break your logic./* WRONG — race on shared counter */
static int counter = 0;
void *bump(void *_) { for (int i = 0; i < 1000000; i++) counter++; return NULL; }
/* RIGHT — atomic */
static _Atomic int counter = 0;
void *bump(void *_) { for (int i = 0; i < 1000000; i++) counter++; return NULL; }
-fsanitize=thread before shipping.Eight recurring threading bugs. Use -pthread, pass args safely, lock around shared state, use while for cond_wait, never return a stack address.