Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@depp
Created April 30, 2015 20:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save depp/241d6f839b799042c409 to your computer and use it in GitHub Desktop.
Save depp/241d6f839b799042c409 to your computer and use it in GitHub Desktop.
Race condition example
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
#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