问题
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.
回答1:
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.
- No O thread can go beyond
P(o_wait)
because o-wait is locked, and should wait. - One random lucky H thread(say H*-1) can go pass
P(mutex)
(now mutex = 0 and count = 1) and and will go insideif(count%2 == 1)
, then up-count 'mutex' (now mutex = 1) and block inP(h_wait)
. (This count actually refers to H count) - Because 'mutex' was up-counted another random H-thread(H*-2) will start to go pass
P(mutex)
(Now mutex = 0 and count =2). But now the count is even -> hence it goes insideelse
. Then it willV(o_wait)
(now o_wait = 1) and stuck inP(h_wait)
. - Now H*-1 is still at the previous position inside
if
block. But because o_wait is up-counted to 1, a lucky O thread(O*) can continue its process. It will do twoV(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). - Now the final values of global variables after completion one molecule, mutex = 1, h_wait = 0 and o_wait = 0, so exactly the initial status. Now the previous process will happen again and again, hence H2O molecules will be created.
I think you get clear with it. Please raise questions if any. :))
来源:https://stackoverflow.com/questions/39664927/semaphores-makewater-synchronization