semaphores makeWater()同步 [英] Semaphores makeWater() synchronization
本文介绍了semaphores makeWater()同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个程序声称解决makeWater()同步问题。但是,我不明白如何。我是新的信号量。
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.
推荐答案
因此,你需要使H2O(2Hs和一个O)组合中同时运行的H线程和O线程数。
So you need to make H2O (2Hs and one O) combinations out of number of simultaneously running H-threads and O-threads.
事情是一个O需要两个H。两个不同的水分子之间没有共享。
The thing is one 'O' needs two 'H' s. And no sharings between two different water molecules.
所以假设O和H线程的数量启动他们的进程。
So assume number of O and H threads start their processes.
- 没有O线程可以超越
P(o_wait)
锁定,并应等待。 - 一个随机幸运的H线程(说H * -1)可以通过
P(mutex)
= 1),并将进入if(count%2 == 1)
,然后向上计数'mutex'(现在mutex = 1) $ c> P(h_wait)。 (这个计数实际上是指H计数) - 因为'mutex'被增加计数,另一个随机H线程(H * -2)将开始通过
P(mutex)
(现在mutex = 0和count = 2)。但现在计数是偶数 - >因此它进入else
。然后它会V(o_wait)
(现在o_wait = 1)并停留在P(h_wait)
。 >
- 现在H * -1仍在
中的上一个位置,如果
阻止。但是因为o_wait被递增计数为1,一个幸运的O线程(O *)可以继续其进程。它将做两个V(h_wait)
s(现在o_wait = 0,h_wait = 2),以便2个以前的H线程可以继续(没有任何其他,现在h_wait = 0 )。因此,所有3(2个H和O)可以完成其过程,而H * -2增加计数'互斥'(现在mutex = 1)。 - 全局变量完成一个分子后,mutex = 1,h_wait = 0和o_wait = 0,所以正好是初始状态。现在前面的过程将会一次又一次地发生,因此会产生H2O分子。
- 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. :))
这篇关于semaphores makeWater()同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文