I am learning the concept of pthread. I wrote a code for the following question :
Implement the following model: Create a master thread. It opens a file. At random intervals, the master thread creates worker threads at random intervals and each worker thread will sleep for random intervals before it reads a line from the file and finally exits.
I wrote the following code :
#include<stdio.h>
#include<pthread.h>
char c;
void *f1(void *f)
{
printf("Calling from thread 1\n");
sleep(rand()%2);
while(c!='\n'&& c!=EOF)
{
printf("1 %c\n",c);
c=getc(f);
}
pthread_exit(NULL);
}
void *f2(void *f)
{
printf("Calling from thread 2\n");
sleep(rand()%2);
while(c!='\n' && c!=EOF)
{
printf("2 %c\n",c);
c=getc(f);
}
pthread_exit(NULL);
}
int main()
{
pthread_t tid1,tid2;
FILE *f;
f=fopen("new.txt","r");
int i;
c=getc(f);
while(c!=EOF)
{
i=rand()%2;
sleep(i);
pthread_create(&tid1,NULL,f1,(void *)f);
i=rand()%2;
sleep(i);
pthread_create(&tid2,NULL,f2,(void *)f);
}
pthread_exit(NULL);
return 0;
}
While executing, the code enters an infinite loop. Sometimes only the first line is being executed then it enters an infinite loop. Even when I used pthread_join
, the problem was not solved.
Why is it entering an infinite loop?