-   Programming (
-   -   problem in uderstanding pthread execution in given code (

Harris_777 09-08-2010 02:38 AM

problem in uderstanding pthread execution in given code
Hi all,

pthread_mutex_t mutex1;
int shared_data = 0;

void *sharedata( void *threadid)

int i;
for(i= 0; i<1024*1024 ;i++)
printf("\nIn shared function%d",shared_data);

int main()

int tid;
void *exitstat;
int t;
int i;

pthread_mutex_init(&mutex1, NULL);

pthread_create(&tid, NULL, sharedata,(void *)&t);

for(i= 0; i<10; i++)
printf("\nShared data is %d", shared_data);

return 0;


I am getting different outputs in main() when I run the same program.Please explain why?
I also want to know at what point the switching takes place between shareddata() and main() function.

Mara 09-08-2010 03:23 PM

Your output is perfectly normal on Linux. The switch moment is generally independent from your code, just like typical process switches. On some implementations of pthread, however, your code matters because the switches are done on system calls and on pthread* functions (in your case it means printf and pthread*).

Harris_777 09-09-2010 12:07 AM

Thanks Mara!!

All times are GMT -5. The time now is 07:35 AM.