I am new to these pthreads. I wrote a program so that instead of displaying the numbers randomly, it should display in order. I have used pthrea_join() method for that. The program is as follows:
int cnt=0,i=1;
pthread_t th[10];
int printmsg()
{
cnt++;
printf( "thread no. %d\n",cnt);
}
void tosync()
{
if(i>0)
pthread_join(th[i-1],NULL); // <---here i am blocking the previous thread..
printmsg();
}
void main(void)
{
pthread_create(&th[0], NULL,(void*)&tosync, NULL);
for( i=1;i<10; i++){
pthread_create(&th[i],NULL, (void*) &tosync, NULL);
}
int y;
for(int i=0; i<10; i++)
pthread_join(th[i],NULL);
return;
}
Still i am getting the numbers randomly…
plzz. help
pthread_join(th[i-1],NULL) this line have some problems. when you create a thread you increate the value of i. suppose
create first three thread OS switch thrid thread start and OS switch to the main thread where it creates rest of threads. after create all threads the value of i is 10/
now suppose OS switch to thrid thread then he waits 10-1 = 9th thread to finish and similary go on.So ultimate it print always randomly. Your strategy is wrong.
try this