Background
I am somewhat confused about my understanding of how condition variables operate in conjunction with concurrent access to shared data. The following is pseudo code to depict my current issue.
// Thread 1: Producervoid cakeMaker(){ lock(some_lock); while(number_of_cakes == MAX_CAKES) wait(rack_has_space); number_of_cakes++; signal(rack_has_cakes); unlock(some_lock);}// Thread 2: Consumervoid cakeEater(){ lock(some_lock); while(number_of_cakes == 0) wait(rack_has_cakes); number_of_cakes--; signal(rack_has_space); unlock(some_lock);}
Let's consider the scenario where the value of number_of_cakes
is 0. As a result, Thread 2
is blocked at wait(rack_has_cakes)
. When Thread 1
runs and increments the value of number_of_cakes
to 1, it signals rack_has_cakes
. However, Thread 2
wakes up before Thread 1
releases the lock on some_lock
, causing it to go back to sleep and miss the signal.
I am unclear about the operation of wait
and signal
. Are they like a toggle switch that gets set to 1 when signal
is called and 0 when wait
succeeds? Can someone explain what is happening behind the scenes?
Question
Can someone walk me through one iteration of the above code step-by-step, with a strong emphasis on the events that occur during the signal
and wait
method calls?