Originally Posted by
Salem
That seems like an idea worth looking into.
I decided to synchronize using a condition variable, up to and all right, now I don't understand why the first text of a file is being read by two threads, which generates the race conditions problem, besides that I had to put the process from the main thread to sleep, stops the time to start another thread and I still have to put a thread on hold which depends exclusively if the amount of line in the file is divisible by 2, I made a debugger with helgrind, but I couldn't find the error
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
/*variable fp, to share the opening of the file and variable c,
to share the reading of the data,
the program has a race condition problem*/
FILE *fp;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *func(void) {
char c;
fp = fopen("file.txt", "r");
if(!fp) {
perror("DEBUG: ");
exit(EXIT_FAILURE);
}
pthread_mutex_lock(&mutex);
while((c = fgetc(fp)) != EOF) {
printf("ID THREAD = %zu CHARACTER= %c\n", pthread_self(), c);
if(c == '\n') {
pthread_cond_wait(&cond, &mutex);
} else {
pthread_cond_signal(&cond);
}
}
pthread_mutex_unlock(&mutex);
}
int main(void) {
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, (void *)func, NULL);
sleep(1);
pthread_create(&thread2, NULL, (void *)func, NULL);
pthread_join(thread2, NULL);
fclose(fp);
return 0;
}
$ cat file.txt
test1
test2
test3
test4
test5
test6