Hi There;
I am facing a thread question.The question is what will be the output of a0, a1 and a2? It is clear that a0=500 and a1=100.The result is as expected. However, value of a2 is changing whenever I run the code. Why? Here is the code:
Code:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#define NTH 5
pthread_mutex_t mutex;
int a0,a1,a2;
void * foo(void * arg)
{
int tindex,i;
int x1 = 0;
int x2 = 7;
tindex = (int) arg;
for(i = 0 ; i < 100 ; i++)
{
pthread_mutex_lock(&mutex);
a0++;
x1++;
pthread_mutex_unlock(&mutex);
x2 += tindex;
}
pthread_mutex_lock(&mutex);
a1 = x1;
a2 = x2;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
return NULL;
}
int main(void)
{
int i;
pthread_t tid[NTH];
a0 = a1 = a2 = 0;
pthread_mutex_init(&mutex,NULL);
for(i=0 ; i<NTH ; ++i)
{
pthread_create(&tid[i] , NULL , foo , (void *) i);
}
for(i=0 ; i<NTH ; ++i)
{
pthread_join(tid[i] , NULL );
}
printf("a0=%d a1=%d a2=%d \n",a0,a1,a2);
return 0;
}
Thanks in advance.