Quantcast
Channel: How exactly does the wait function work wrt to condition variables - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Answer by ol202020 for How exactly does the wait function work wrt to condition variables

$
0
0

Lets say we currently have number_of_cakes = 0, so Thread 2 is currently stuck on wait(rack_has_cakes). Thread 1 runs and increments number_of_cakes by 1. Then it calls signal(rack_has_cakes) - this wakes up Thread 2, unfortunately Thread 2 wakes up before Thread 1 calls unlock(some_lock), so it goes back to sleep again and the signal has been missed.

You are right, that might be happens, because your signal command order was not correct.In both Producer and Consumer, you have set the following order of commands:

signal(rack_has_cakes);unlock(some_lock);

But the order should be:

unlock(some_lock);signal(rack_has_cakes);

You first have to unlock the mutex and then signal the other thread.Since signal command is condition variable wait() and signal() commands are thread safe, you should not worry about releasing the lock before.

But this step is very important as it give the other thread a chance to lock the mutex.


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>