pathterminuspages/notes/aboutcontactabout me

Race Conditions

13.01.2018

Even though a multi threaded program do not share state, problems can occur. Observe the following program:

#include <stdio.h> #include <stdlib.h> #include <pthread.h> void *threadF(void *arg){ int myid = *((int *)arg); printf("Hello from thread : %d\n",myid); return NULL; } int main(){ pthread_t tids[10]; int i; for(i = 0; i < 10; i++){ pthread_create(&tids[i],NULL,threadF,&i); } for(i = 0; i < 10; i++){ pthread_join(tids[i],NULL); } return 0; }

Which gives:

Out : Hello from thread : 3 Hello from thread : 3 Hello from thread : 3 Hello from thread : 4 Hello from thread : 5 Hello from thread : 6 Hello from thread : 8 Hello from thread : 9 Hello from thread : 9 Hello from thread : 0

These kinds of problems is known as race conditions. The following happens: The main thread increases i, creates a thread and passes i as a pointer. Now either the main thread keeps control, or control is passed to the new thread. If the first case happens, i is incremented again, a new thread is created and to which control is passed is again decided. But when those threads who were skipped, finally are passed control, i, to which the pointer for all threads points, has been incremented more than supposed.

This problem has two solutions. The one is to allocate memory using malloc before creating each thread. It's important in this case to free again in threadF since otherwise the allocated integer might be freed before control is passed to the appropriate thread. The other solution is to pass the value of i in the address as so:

#include <stdio.h> #include <stdlib.h> #include <pthread.h> void *threadF(void *arg){ long myid = (long) arg; printf("Hello from thread : %ld\n",myid); return NULL; } int main(){ pthread_t tids[10]; long i; for(i = 0; i < 10; i++){ pthread_create(&tids[i],NULL,threadF,(void *) i); } for(i = 0; i < 10; i++){ pthread_join(tids[i],NULL); } return 0; }

where i is defined as a long to fit the size of the pointer (to avoid warnings).

CommentsGuest Name:Comment: