I'm learning to use pthreads, mutexes and condition variables but things aren't going as expected.
MAIN THREAD: runs continuously, signals worker thread, reads from file_A.
WORKER THREAD: sleep until signal received, writes to file_A, back to sleep (should be repeatable)
So I understand a mutex is needed here to prevent both threads from reading/writing to and from the same file. I'm using a condition variable to signal the worker thread.
But for some reason, the worker thread only runs once. Do I need to reset the condition variable or do something else?
Worker thread function:
void* WriteTime(){
pthread_mutex_lock(&mutex);
pthread_cond_wait(&condition, &mutex);
/* Open File, Write to File, Close File */
pthread_mutex_unlock(&mutex);
}
Main Thread:
pthread_t timeThread;
pthread_create(&timeThread, NULL, &WriteTime, NULL);
while(gameConditionFulfilled == false){
/* Print status, gets user input into line */
/* If user enters "time", wake up WORKER_THREAD */
if(strcmp(line, "time")==0){
pthread_mutex_lock(&mutex);
pthread_cond_signal(&condition);
/* Read from file, print data, close file */
pthread_mutex_unlock(&mutex);
}
}
Also my understanding of the code above is like this:
- Worker thread locks mutex. (Launched before main's loop)
- Worker thread cond_wait unlocks mutex and waits for condition.
- Main thread locks mutex.
- Main thread signals condition.
- Worker thread regains mutex lock, writes to file.
- Worker thread unlocks mutex.
- Main thread regains mutex and locks it.
- Main thread reads file.
- Main thread unlocks mutex.
- Worker thread regains lock?
The behavior is actually:
- Main thread reads from file
- Worker thread wakes up, writes to file, never runs again