Created
April 30, 2015 20:56
-
-
Save depp/241d6f839b799042c409 to your computer and use it in GitHub Desktop.
Race condition example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This is what happens when I run the program. Note that 2 and 4 appear twice, but 0 and 1 never appear. The output is non-deterministic, because there is a race condition, the output could be almost anything. | |
Arg = 2 | |
Arg = 4 | |
Arg = 3 | |
Arg = 5 | |
Arg = 6 | |
Arg = 2 | |
Arg = 7 | |
Arg = 8 | |
Arg = 9 | |
Arg = 4 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pthread.h> | |
#include <stdio.h> | |
#define N 10 | |
void *thread_func(void *arg) | |
{ | |
int *ptr = arg; | |
printf("Arg = %d\n", *ptr); | |
return NULL; | |
} | |
int main() | |
{ | |
int i; | |
pthread_t threads[N]; | |
for (i = 0; i < N; i++) { | |
pthread_create(&threads[i], NULL, thread_func, &i); | |
} | |
for (i = 0; i < N; i++) { | |
pthread_join(threads[i], NULL); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment