This program claims to solve makeWater() synchronization problem. However, I could not understand how. I am new in semaphores. I would appriciate if you can help me to understand this code.
So you need to make H2O (2Hs and one O) combinations out of number of simultaneously running H-threads and O-threads.
The thing is one 'O' needs two 'H' s. And no sharings between two different water molecules.
So assume number of O and H threads start their processes.
P(o_wait)
because o-wait is locked, and should wait. P(mutex)
(now mutex = 0 and count = 1) and and will go inside if(count%2 == 1)
, then up-count 'mutex' (now mutex = 1) and block in P(h_wait)
. (This count actually refers to H count)P(mutex)
(Now mutex = 0 and count =2). But now the count is even -> hence it goes inside else
. Then it will V(o_wait)
(now o_wait = 1) and stuck in P(h_wait)
.if
block. But because o_wait is up-counted to 1, a lucky O thread(O*) can continue its process. It will do two V(h_wait)
s (Now o_wait = 0, h_wait = 2), so that 2 previous H threads can continue(No any other, now h_wait = 0). So all 3 (2 Hs and O) can finish its process, while H*-2 is up-counting the 'mutex' (now mutex = 1).I think you get clear with it. Please raise questions if any. :))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With