I am working on an assignment which requires me to 1. Open a file and read from it in one thread, 2. As each value is read one by one save each value to a global variable and then initiate a mutex so 3. The second thread can use that global variable write it to a file before the next value is read by thread 1 and the process repeats. I am having trouble timing up my mutex so that once a value is read it can be written by the second thread. Presently, thread 2 only prints out 0 and it isn't iterating through. I am not sure what I am doing wrong. What I am thinking is that when I lock the thread it is rapidly iterating before going to thread 2. Here is my source code:
#include <stdio.h>
#include <stdio.h>
#include <pthread.h>
int value;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *inputThread(void * args) {
FILE *input = fopen("hw4.in", "r");
while(!feof(input)) {
//printf("Thread locked.\n");
fscanf(input, "%d\n", &value);
pthread_mutex_lock(&mutex);
printf("value: %d\n", value);
//printf("Thread unlocked.\n");
pthread_mutex_unlock(&mutex);
}
fclose(input);
pthread_exit(NULL);
}
void *counting(void *args) {
printf("Value: %d\n", value);
pthread_exit(NULL);
}
int main() {
//Creating thread1
pthread_t pt1;
pthread_create(&pt1, NULL, inputThread, NULL);
//Creating thread2
pthread_t pt2;
pthread_create(&pt2, NULL, counting, NULL);
//Joining thread1
pthread_join(pt1, NULL);
pthread_join(pt2, NULL);
}
EDIT: Would the proper way to do this be for thread2 to also call inputThread and in the while loop lock the mutex and after the while loop write another statement to write to the file and close the mutex after that? As in I have to do both operations within the same function?