I am facing a problem in multi-threading. Please consider the following code:
#include<stdio.h>
#include<pthread.h>
void* functionA(void*);
void* functionB(void*);
int main()
{
pthread_t tid[2];
pthread_attr_t arg;
for(int i = 0; i<2; ++i)
{
pthread_attr_init(&arg);
if(i == 0)
{
int x = 0;
pthread_create(&tid[i], &arg, functionA, (void*)&x);
}
else if(i == 1)
{
int x = 6;
pthread_create(&tid[i], &arg, functionB, (void*)&x);
}
}
// wait for both threads to finish execution...
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
return 0;
}
//.........................DEFINATIONS........................
void* functionA(void* x)
{
int Index = *((int*)x);
printf("First: %d\n",Index); //..................... LINE M
}
void* functionB(void* x)
{
int Index = *((int*)x);
printf("Second: %d\n",Index); //....................... LINE N
}
Now I believe that functionA will start its execution first, because ofcourse thread for functionA will be created first in for loop, so according to me the output should be:
First: 0 (from Line M)
Second: 6 (from Line N)
but the actual output is,
Second: 6
First: 6
Now I am really surprised to see this, and I don't know what's happening. Not only secondFunction start its execution first, but also both the functions are showing same value i.e. 6, and it doesn't make sense to me. Can anyone please Explain me what is going on here???? Thanks in advance...