Semaphore to control access to a critical section. : Semaphore « Thread « Python Tutorial






import threading
import random
import time

class SemaphoreThread( threading.Thread ):
   availableTables = [ "A", "B", "C", "D", "E" ]   

   def __init__( self, threadName, semaphore ):
      threading.Thread.__init__( self, name = threadName )
      self.sleepTime = random.randrange( 1, 6 )
      self.threadSemaphore = semaphore     

   def run( self ):
      self.threadSemaphore.acquire()

      table = SemaphoreThread.availableTables.pop()
      print "%s entered; seated at table %s."  % ( self.getName(), table ), 
      print SemaphoreThread.availableTables

      time.sleep( self.sleepTime )   # enjoy a meal

      print "   %s exiting; freeing table %s." % ( self.getName(), table ),
      SemaphoreThread.availableTables.append( table )
      print SemaphoreThread.availableTables

      self.threadSemaphore.release()

threads = [] 

threadSemaphore = threading.Semaphore(len( SemaphoreThread.availableTables ) )

for i in range( 1, 11 ):
   threads.append( SemaphoreThread( "thread" + str( i ),threadSemaphore ) )

for thread in threads:
   thread.start()








17.4.Semaphore
17.4.1.Semaphore to control access to a critical section.