Condition Variables

The Condition object

  • Creates a condition variable.
  • Synchronization primitive typically used when a thread is interested in an event or state change.
  • Classic problem: producer-consumer problem.
     # Create data queue and a condition variable
     data = []
     cv = threading.Condition()
     # Consumer thread
     def consume_item():
         cv.acquire()            # Acquire the lock
         while not len(data):
              cv.wait()          # Wait for data to show up
         r = data.pop()
         cv.release()            # Release the lock
         return r
     # Producer thread
     def produce_item(obj):
         cv.acquire()           # Acquire the lock
         data.append(obj)
         cv.notify()            # Notify a consumer
         cv.release()           # Release the lock 
<<< O'Reilly OSCON 2000, Advanced Python Programming, Slide 76
July 17, 2000, beazley@cs.uchicago.edu
>>>