LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   problem in uderstanding pthread execution in given code (http://www.linuxquestions.org/questions/programming-9/problem-in-uderstanding-pthread-execution-in-given-code-830906/)

Harris_777 09-08-2010 01:38 AM

problem in uderstanding pthread execution in given code
 
Hi all,
#include<stdio.h>
#include<pthread.h>

program
**********
pthread_mutex_t mutex1;
int shared_data = 0;

void *sharedata( void *threadid)
{

int i;
for(i= 0; i<1024*1024 ;i++)
{
pthread_mutex_lock(&mutex1);
shared_data++;
pthread_mutex_unlock(&mutex1);
}
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++)
{
//sleep(1);
pthread_mutex_lock(&mutex1);
printf("\nShared data is %d", shared_data);
pthread_mutex_unlock(&mutex1);
}

pthread_join(tid,&exitstat);
return 0;
}


output
******

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 02: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-08-2010 11:07 PM

Thanks Mara!!


All times are GMT -5. The time now is 11:09 PM.