I have the below snippet of code with which I want to use to show the case of data racing in the C multithreading programming. And I compiled and ran it with gcc test.c -O0 -lpthread -o test && ./test on an x86 Linux system (with only a single core), for near a hundred times, but I didn't see any case that the printed value is incorrect (200000). Does it mean that the x86 or the compiler could guarantee that every modification on an int variable is thread-safe? Or anything wrong with my program?
Edit: so, as @Sinic and I tested, the question would be updated to: Why does data racing rarely happen on a single-core CPU? Or there won't be any data racing issues on a single-core CPU? Because, AFAIK, the threads would be scheduled randomly even on a single-core CPU. So, the result would be a mess as well.
// test.c
#include <threads.h>
#include <stdio.h>
#define THREAD_COUNT 20
#define THREAD_LOOP 10000
int counter = 0;
int run(void* data) {
for (int i = 0; i < THREAD_LOOP; i++)
counter++; // <- each thread would modify the global variable counter here.
printf("Thread %d terminates.\n", *((int*) data));
return thrd_success;
}
int main(void) {
#ifndef __STDC_NO_THREADS__
int ids[THREAD_COUNT];
thrd_t threads[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
ids[i] = i + 1;
thrd_create(&threads[i], run, ids + i);
}
for (int i = 0; i < THREAD_COUNT; i++)
thrd_join(threads[i], NULL);
printf("Counter value is: %d.\n", counter);
#endif
return 0;
}
Got a snapshot of the assembly code of the run function as shown below, and also pointed out the corresponding code for counter++.
