Understanding race conditions
What you'll learn: You will understand why unpredictable bugs occur when multiple threads try to modify the same piece of memory at the same time.
The Shared Notepad Problem
Imagine you and a friend are both tasked with updating a single tally mark on a notepad. To update it, you must follow three steps:
- Look at the current number.
- Mentally add one to that number.
- Write the new number down.
If you work one after the other, the tally works perfectly. But if you both look at the notepad at the exact same time, you both see "10." You both mentally calculate "11." You both write "11" on the paper. Even though two people performed the work, the count only increased by one.
This is a race condition. The outcome of your program depends on the "race" of which thread finishes its steps first.
Race Conditions in Code
In C, a simple line like counter++; looks like a single step. However, at the CPU level, the computer must load the value from memory into a register, increment it, and store it back.
If two threads execute these assembly-level steps simultaneously, they can overlap, leading to "lost updates."
#include <stdio.h>
#include <pthread.h>
int global_counter = 0;
void* increment_task(void* arg) {
for (int i = 0; i < 100000; i++) {
// This is the "Critical Section"
// Multiple threads racing here will cause data corruption
global_counter++;
}
return NULL;
}
int main() {
pthread_t t1, t2;
pthread_create(&t1, NULL, increment_task, NULL);
pthread_create(&t2, NULL, increment_task, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
// You expect 200000, but you will likely get a smaller, random number
printf("Final count: %d\n", global_counter);
return 0;
}
Why They are Dangerous
Race conditions are the most hated bugs in systems programming because they are nondeterministic. Your code might work perfectly 99% of the time during testing, but crash or produce wrong results in production when the CPU timing shifts slightly.
To fix this, we need a way to ensure that only one thread can access the "notepad" at a time. In the next lesson, we will look at Mutexes, the "locks" that prevent these races from happening.
Key takeaway
A race condition occurs when the timing of threads affects the correctness of your data, usually resulting in lost updates or corrupted memory.