I've just started studying monitors and condition variables in C and I can't understand how the following code works. I have the following implementation of the wait_condition and signal_condition functions for a condition variable
struct Monitor {
//id of the mutex semaphore for the monitor
int mutex;
int num_var_cond;
//id of the semaphores of the condition variables
int id_conds;
//array of the condition_count (they count number of processes suspended on a CV)
int *cond_counts;
//id shared memory
int id_shared;
};
void wait_condition(Monitor* M,int id_var) {
M->cond_counts[id_var]=M->cond_counts[id_var]+1;
Signal_Sem(M->mutex,0);
Wait_Sem(M->id_conds,id_var);
M->cond_counts[id_var]=M->cond_counts[id_var]-1;
}
void signal_condition(Monitor* M,int id_var){
if(M->cond_counts[id_var]>0){
Signal_Sem(M->id_conds,id_var);
}else{
Signal_Sem(M->mutex,0); }
}
What I'm trying to understand is when I use signal_condition on a process that was suspended earlier with a wait_condition shouldn't there be another wait_sem(M->mutex, 0) otherwise the mutex has value 1 and the monitor is not occupied
I expected to be another wait_sem(M->mutex, 0) after the wait_sem(M->id_conds, id_var) in the wait_condition to keep the monitor occupied