title: in this Semaphore example ,Is it necessary to lock for refill() and buy()?
body: <p>in this Semaphore example ,Is it necessary to lock for refill() and buy() ?</p>
  
  <p>the Book said :
  The refill() function is performed when the owner of the fictitious vend-
  ing machines comes to add one more item to inventory. The entire routine
  represents a critical section; this is why acquiring the lock is the only way
  to execute all lines.</p>
  
  <p>but I think it is ot necessary to lock for refill() and buy() 
  what about your opinion ?</p>
  
  <pre><code>#!/usr/bin/env python
  
  from atexit import register
  from random import randrange
  from threading import BoundedSemaphore, Lock, Thread
  from time import sleep, ctime
  
  lock = Lock()
  MAX = 5
  candytray = BoundedSemaphore(MAX)
  
  def refill():
     # lock.acquire()
      try:
          candytray.release()
      except ValueError:
          pass
      #lock.release()
  
  def buy():
  
      #lock.acquire()
      candytray.acquire(False)
      #lock.release()
  
  def producer(loops):
      for i in range(loops):
          refill()
          sleep(randrange(3))
  
  def consumer(loops):
      for i in range(loops):
          buy()
          sleep(randrange(3))
  
  def _main():
      print('starting at:', ctime())
      nloops = randrange(2, 6)
      print('THE CANDY MACHINE (full with %d bars)!' % MAX)
      Thread(target=consumer, args=(randrange(nloops, nloops+MAX+2),)).start() # buyer
      Thread(target=producer, args=(nloops,)).start() # vendor
  
  @register
  def _atexit():
      print('all DONE at:', ctime())
  
  if __name__ == '__main__':
      _main()
  </code></pre>