I have a Read thread and multiple write threads as the following.
Read thread:
pthread_mutex_lock(mutex);
while(1){
pthread_cond_wait(cond, mutex);
switch(state){
//do something
}
}
pthread_mutex_unlock(mutex);
Write thread1:
pthread_mutex_lock(mutex);
state = work;
pthread_cond_signal(cond);
//do something
pthread_mutex_unlock(mutex);
Write thread2:
pthread_mutex_lock(mutex);
state = lunch;
pthread_cond_signal(cond);
//do something
pthread_mutex_unlock(mutex);
Assume state
is the shared variable and Read thread goes into waiting before all the write threads.
Say the two write threads try to get mutex
at the same time and write1 acquires mutex
and sends cond
. At this point of time both write2 and read threads are locked on the mutex
, and so far to my understanding, no thread has a priority to the mutex
so we can't be sure when write1 releases the mutex
that read thread will acquire it, which will lead to a missed signal and an overwritten state.
I have two questions here:
- Is my understanding correct, that the above situation is possible?
- If so, how do I make sure that no signal is missed in my code ?