Sunday 15 January 2012

python - in this Semaphore example ,Is it necessary to lock for refill() and buy()? -


In this semaphore example, is it necessary to refill () and lock to buy?

The book said: The refill () function is performed when the owner of the fake sells comes to add another item to the list. The entire routine represents an important segment; This is the reason that the only way to get lock is to execute all the lines.

But I think it is necessary to lock to fill it again () and buy () about your opinion? import from importer, import imported import from the interval import register by #! / Usr / bin / env python import import gold bags, lock, lock = lock () max = 5 canditai = badassamophore (max) DEF refill (): # lock.acquire () try: except valueError : Candytray.release (): pass # lock.release () def buy (): # lock.acquire () candytray.acquire (False) # lock.release () Diff Producer (Loop): For loop in range: Refill (Sleep) (Randrange (3)) DIF Consumer (Loop): In range (loop) I: To buy (sleep (Randrange (3)) def _main (): Print ('Starting from:', ctime ()) Nloops = randrange (2, 6) print ('candy machine (Full with% d times)! '% MAX' thread (target = consumer, args = (Randomization (Nullops, NLops + Max + 2))). Start () # Buyer thread (target = creator, args = ( Nullops,)). Start () # Seller @register def _atexit (): print ('All done at:', ctime ()) If __name__ == '__main__': _main ()

itemprop = "text">

A lock is absolutely essential, maybe it will help you if you have the number of candies left after each productive / consumer call To print New codes have changed little.

I for

  numcandies = 5   

refill:

(<> Buy:% d left "% numcandies")

There is no output without locks (that data race issue ):

  ('Starting from:', 'Mars Mar 26 23:09:41 2013') Candy Machine (complete with 5 bars)! Buy: 4 left again Fill: 5 remaining refill: 6 Buy left: Buy left: 4 left Buy: 3 Leave refill: 6 left Refill: 7 Buy left: 6 left ('Finish:' Between the call of the Creator  and between the actual update of the  numcandies  counter, on March 26 23: 09:43, 2013 ')   

If we have no control over the order of 2 continuously Consumer

without locking, which actually modifies the counter, in the above case, even if < Code> numcandies was updated to 3 purchased consumer , there is still a local copy of 5 in producer . After updating, it sets counter to 6, which is completely false

No comments:

Post a Comment