I have created a C program which will read 20000 strings from a text file, and send it to other program. I have used a while to loop through this text file and create threads which will send that text to the other program. But I want only 4 threads to work. so I have used a counter and keep decrementing it, and an if condition to check the counter and when it will be set to 1 then I have called pthread_join for the previous threads. I want to first finish these 4 threads and then new 4 threads to pick up the new text file strings. But it is not working as I need. it processes only every 4th thread 4 times. and doesnt picks up all records from the text file.
Program:-
int Read_record()
{
printf("Inside Read_record()\n");
pthread_t threads;
int rc;
char l_record[300];
int thNum=4;
while(1){
MEMSET(g_record);
if(fgets(g_record,300,g_r_fp)==NULL){
printf("End of File.\n");
break;
}else{
//printf("%s",g_record);
printf("%s",g_record);
rc = pthread_create(&threads, NULL, &Get_report, (void *)g_record);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
thNum--;
}
if(thNum==0){
pthread_join(threads, NULL);
thNum=4;
}
}
return 0;
}
Input Text file contains: 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Out put comes:-
Inside Read_record()
1
2
3
4
Inside Get_report, wget 4
Inside Get_report, wget 4
Inside Get_report, wget 4
Inside Get_report, wget 4
5
6
7
8
Inside Get_report, wget 8
Inside Get_report, wget 8
Inside Get_report, wget 8
Inside Get_report, wget 8
9
10
11
12
Inside Get_report, wget 12
Inside Get_report, wget 12
Inside Get_report, wget 12
Inside Get_report, wget 12
13
14
15
16
Inside Get_report, wget 16
Inside Get_report, wget 16
Inside Get_report, wget 16
Inside Get_report, wget 16
17
18
19
20
Inside Get_report, wget 20
Inside Get_report, wget 20
Inside Get_report, wget 20
Inside Get_report, wget 20
End of File.
Desire Output:-
Inside Get_report, wget 1
Inside Get_report, wget 2
Inside Get_report, wget 3
Inside Get_report, wget 4
Inside Get_report, wget 5
Inside Get_report, wget 6
Inside Get_report, wget 7
Inside Get_report, wget 8
Inside Get_report, wget 9
Inside Get_report, wget 10
Inside Get_report, wget 11
Inside Get_report, wget 12.
and so on..
Please mind I want only 4 threads to create in system. not more than that.