I have a code to simulate serial vs parallel computing. However, it seems has a race condition.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
void *foo(void *para) {
printf("This is Thread %d running...\n", *(size_t *)para);
fflush(stdout);
sleep(2);
}
int main(void)
{
/* loop version
for (size_t i = 0; i < 4; i++) {
foo((void *)&i);
}
*/
pthread_t pool[4];
for (size_t i = 0; i < 4; i++) {
pthread_create(&pool[i], NULL, foo, (void *)&i);
}
for (size_t i = 0; i < 4; i++) {
pthread_join(pool[i], NULL);
}
return 0;
}
Output:
[william@Notebook Downloads]$ time ./a.out
This is Thread 1 running...
This is Thread 2 running...
This is Thread 4 running...
This is Thread 3 running...
real 0m2.003s
user 0m0.003s
sys 0m0.000s
[william@Notebook Downloads]$ time ./a.out
This is Thread 3 running...
This is Thread 3 running...
This is Thread 2 running...
This is Thread 4 running...
real 0m2.003s
user 0m0.003s
sys 0m0.000s
Most of examples when race condition happens is whenn you have multiple threads try to write a shared value. However, there is no write operation in this code at all. So, why this happens? Is it because for loop is not excuted in serial order?