Semaphore Objects

Semaphores

  • A locking primitive based on a counter.
  • Each acquire() method decrements the counter.
  • Each release() method increments the counter.
  • If the counter reaches zero, future acquire() methods block.
  • Common use: limiting the number of threads allowed to execute code
     sem = threading.Semaphore(5)     # No more than 5 threads allowed
     def fetch_file(host,filename):
         sem.acquire()                # Decrements count or blocks if zero
         ...
         blah
         ...
         sem.release()                # Increment count 
<<< O'Reilly OSCON 2000, Advanced Python Programming, Slide 77
July 17, 2000, beazley@cs.uchicago.edu
>>>