Semaphore to control access to a critical section. : Semaphore : Thread PYTHON TUTORIALS


PYTHON TUTORIALS » Thread » Semaphore »

 

Semaphore to control access to a critical section.


import threading
import random
import time

class SemaphoreThreadthreading.Thread ):
   availableTables = "A""B""C""D""E" ]   

   def __init__self, threadName, semaphore ):
      threading.Thread.__init__self, name = threadName )
      self.sleepTime = random.randrange1)
      self.threadSemaphore = semaphore     

   def runself ):
      self.threadSemaphore.acquire()

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

      time.sleepself.sleepTime )   # enjoy a meal

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

      self.threadSemaphore.release()

threads = [] 

threadSemaphore = threading.Semaphore(lenSemaphoreThread.availableTables ) )

for i in range111 ):
   threads.appendSemaphoreThread"thread" + str),threadSemaphore ) )

for thread in threads:
   thread.start()



Leave a Comment / Note


 
Verification is used to prevent unwanted posts (spam). .


PYTHON TUTORIALS

 Navioo Thread
» Semaphore