I was practicing some multithreaded programs, but I could not figure the logic behind this output.
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
int print_message(void* ptr);
int main()
{
pthread_t thread1,thread2;
char *mesg1 = "Thread 1";
char *mesg2 = "Thread 2";
int iret1, iret2;
pthread_create(&thread1, NULL, print_message, (void *)mesg1);
pthread_create(&thread2, NULL, print_message, (void *)mesg2);
pthread_join(thread1,(void*)&iret1 );
pthread_join(thread2, (void*)&iret2);
printf("Thread 1 return : %d\n", (int)iret1);
printf("Thread 2 return : %d\n", (int)iret2);
return 0;
}
int print_message(void *ptr)
{
char *mesg;
static int i=0;
mesg = (char *)ptr;
printf("%s\n",mesg);
i++;
return ((void*)i);
}
I was expecting the output
Thread 1
Thread 2
Thread 1 return : 1
Thread 2 return : 2
but I am getting the output
Thread 1
Thread 2
Thread 1 return : 0
Thread 2 return : 2
Could some please clarify this to me ? And please point if any errors in usage of pthread functions.
The variable
iis shared between both threads because it isstatic. The behaviour of modifying a variable between multiple threads is undefined, so, in fact, both the output you get and the output you want to get are “wrong” in the sense that the compiler is under no obligation to give it to you. In fact, I was able to get the output to change depending on the optimisation level I used and it will undoubtedly be different based on the platform.If you want to modify
i, you should use a mutex:If you do not use a mutex, you will never be sure to get the output you think you should get.