Race Condition
A race condition is a bug whose outcome depends on the unpredictable timing of threads, signals, or events. The program is logically wrong under some interleavings even when every single access is free of data races.
Detailed Explanation
People say "race" for two different things. A data race is the C11 undefined-behavior kind: conflicting unsynchronized accesses to one object. A race condition is the broader logic kind: check-then-act, time-of-check/time-of-use, two threads both thinking they won.
Example: thread A reads if (slot == NULL), thread B does the same, both allocate, both write. If slot is _Atomic or protected by a mutex, there is no data race. There is still a race condition: one allocation is lost, or two objects are created when you wanted one. The fix is to make the check and the act one critical section, or to use compare_exchange so only one thread installs the pointer.
TOCTOU on files is the same shape across processes: access(path) then open(path) lets an attacker swap the file. The fix is to open with the right flags and operate on the descriptor, not to add a sleep.
Signal handlers are races against the interrupted thread. A handler that sets a volatile sig_atomic_t flag is the safe pattern. A handler that calls malloc or printf races the interrupted heap or stdio.
Not every race condition is a data race, and not every timing-dependent bug is either. A missed condvar signal is a race condition (the waiter arrived after the signal). Fixing it is a while loop on a predicate, not an atomic on the condvar.
Detecting logic races is harder than detecting data races. ThreadSanitizer finds data races. Logic races need asserts on invariants, stress tests with more threads than cores, and code review of check-then-act.
Code Examples
#include <stdatomic.h>
#include <stdio.h>
static _Atomic int *slot;
/* Check-then-act: both callers can pass the NULL check. No data race on
slot if we use atomics, but two objects can be created. */
static int install(int *p)
{
int *expected = NULL;
if (atomic_compare_exchange_strong(&slot, &expected, p)) {
return 1; /* we won */
}
return 0;
}
int main(void)
{
int a = 1, b = 2;
printf("%d %d\n", install(&a), install(&b));
/* prints: 1 0 */
return 0;
}Common Gotchas
Fixing a data race with `_Atomic` does not fix a check-then-act race
you still need a single combined operation or a lock around both steps.
`sleep` is not synchronization
it changes the odds and hides the bug in testing.
A signal handler is concurrent with the thread it interrupted
only async-signal-safe functions, or a flag.
Two `malloc`s and two stores into one pointer without a CAS or a lock leak one o
Two `malloc`s and two stores into one pointer without a CAS or a lock leak one object and confuse ownership