Data Race
A data race happens when two threads access the same memory, at least one access is a write, and the accesses are not both atomic and not separated by synchronization. In C the program then has undefined behavior.
Detailed Explanation
C11's memory model is blunt. If two threads conflict on a non-atomic object without a happens-before edge between the accesses, the entire program is undefined. The compiler may delete later code, invent loads, or tear a 64-bit store. "I have only seen a wrong count" is the lucky outcome.
Synchronization means a mutex lock that happens after the matching unlock, an acquire load that sees a release store, joining a thread (which happens after that thread's last access), or the start of a thread (which happens after pthread_create returns in the parent). volatile is not on that list. A bare int flag is not on that list.
Two atomic operations on the same _Atomic object do not form a data race, regardless of memory order. They can still form a logic race. Two non-atomic accesses to different objects never form a data race with each other; false sharing can still make them slow.
Benign data races are a myth in C. The "I only write a bool" pattern is a data race. The "I only read while another thread writes, I can live with a stale value" pattern is a data race. Use _Atomic with relaxed if you truly want a possibly stale but defined value.
ThreadSanitizer (-fsanitize=thread) is the tool. It is not perfect with mmap and some lock-free patterns, and it wants -pthread and little or no volatile cleverness. Run it on tests that actually start two threads.
Single-threaded programs do not have data races. Signal handlers and fork after threads complicate the story; treat a handler as a second thread for this definition, except that only atomics of sig_atomic_t and a short list of functions are allowed.
Code Examples
#include <pthread.h>
#include <stdio.h>
static int bad; /* non-atomic, shared */
static void *inc(void *arg)
{
(void)arg;
for (int i = 0; i < 100000; i++) {
bad++; /* data race if two threads run this */
}
return NULL;
}
int main(void)
{
pthread_t a, b;
pthread_create(&a, NULL, inc, NULL);
pthread_create(&b, NULL, inc, NULL);
pthread_join(a, NULL);
pthread_join(b, NULL);
printf("%d\n", bad); /* may print not 200000; UB either way */
return 0;
}#include <stdatomic.h>
#include <stdio.h>
int main(void)
{
_Atomic int ok = 0;
atomic_store(&ok, 1);
printf("%d\n", atomic_load(&ok)); /* prints: 1 — no data race */
return 0;
}Common Gotchas
A data race is undefined behavior, not a "racy but defined read"
the compiler may assume the other thread does not exist and delete your check.
Joining a thread after the race does not retroactively define it
happens-before must cover the accesses themselves.
Adjacent bit-fields in one word can race even if you name different fields
the compiler may touch the whole word.