Semaphores makeWater() synchronization
Asked Answered
T

1

4

MakeWater() synchronization pseudocode

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.

Turbit answered 23/9, 2016 at 15:53 Comment(0)
F
7

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 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)
  • 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 inside else. Then it will V(o_wait)(now o_wait = 1) and stuck in P(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 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).
  • 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. :))

Fleabag answered 24/9, 2016 at 10:9 Comment(2)
It is a great explanation =) I've understood very well! Thanks a lot Supun @Supun WijerathneTurbit
@Turbit always nice to see (Y) :))Fleabag

© 2022 - 2024 — McMap. All rights reserved.