Free cookie consent management tool by TermsFeed Condition variables in Python | Pythontic.com

Condition variables in Python

Overview:

  • A Condition variable signals a predicate becoming true which wakes up the threads waiting for such states. For example, availability of an item in a list is a predicate which can be signaled to a thread waiting for that state.
  • A thread can be made to wait for a predicate to become True through the wait() method of the Condition object.
  • Signaling of a condition, a predicate becoming true is communicated through the notify() method of the Condition object.
  • Prior to waiting on a condition object, the associated lock must be acquired by the calling thread.
  • After notify() the lock must be released by the calling thread.

Example:

# Example Python program that uses a condition variable 
# to signal from a producer thread to a consumer thread
import threading as th
import time

items = []
count = 0
shouldExit = False

# Function defintion for the producer thread
def produce(cv):
    global count
    global shouldExit

    while(True):
        cv.acquire()
        count += 1
        item = "Item %d"%count 
        items.append(item)
        print("Produced:%s"%item)
        if(count >= 10):
            shouldExit = True
            cv.notify()
            cv.release()
            break        
        cv.notify()
        cv.release()
        time.sleep(2)

# Function defintion for the consumer thread
def consume(cv):
    #with cv:
    global shouldExit
    while(True):
        print("Pre-wait")
        cv.acquire()
        cv.wait()
        item = items.pop()
        print("Consumed:%s"%item)

        if(shouldExit == True):
            print("Consumer: This wakeup is for pop + exit")
            cv.release()
            break        

        cv.release()

# Create a lock            
lock = th.Lock()

# Create a condition variable
cond = th.Condition(lock)

# Create a producer thread
producer = th.Thread(target = produce, args = (cond,))

# Create a consumer thread
consumer = th.Thread(target = consume, args = (cond,))

# Start the consumer and producer threads
consumer.start()
producer.start()

# Wait for the child threads to complete
producer.join()
consumer.join()

print("Producer and consumer threads exited")
print("Main thread exiting")

Output:

Pre-wait
Produced:Item 1
Consumed:Item 1
Pre-wait
Produced:Item 2
Consumed:Item 2
Pre-wait
Produced:Item 3
Consumed:Item 3
Pre-wait
Produced:Item 4
Consumed:Item 4
Pre-wait
Produced:Item 5
Consumed:Item 5
Pre-wait
Produced:Item 6
Consumed:Item 6
Pre-wait
Produced:Item 7
Consumed:Item 7
Pre-wait
Produced:Item 8
Consumed:Item 8
Pre-wait
Produced:Item 9
Consumed:Item 9
Pre-wait
Produced:Item 10
Consumed:Item 10
Consumer: This wakeup is for pop + exit
Producer and consumer threads exited
Main thread exiting

 


Copyright 2025 © pythontic.com