Get The Most Affordable Hosting in the World!

Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.

Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!

Get Started Now!

Threads share the memory allocated to a process. As a result, threads in the same process can communicate with each other. To facilitate inter-thread communication, the threading module provides Event object and Condition object.

The Event Object

An Event object manages the state of an internal flag. The flag is initially false and becomes true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true.

Methods of Event object −

is_set() method

Return True if and only if the internal flag is true.

set() method

Set the internal flag to true. All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all.

clear() method

Reset the internal flag to false. Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again.

wait(timeout=None) method

Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds.

Example

The following code attempts to simulate the traffic flow being controlled by the state of traffic signal either GREEN or RED.

There are two threads in the program, targeting two different functions. The signal_state() function periodically sets and resets the event indicating change of signal from GREEN to RED.

The traffic_flow() function waits for the event to be set, and runs a loop till it remains set.

 
from threading import * import time def signal_state(): while True: time.sleep(5) print("Traffic Police Giving GREEN Signal") event.set() time.sleep(10) print("Traffic Police Giving RED Signal") event.clear() def traffic_flow(): num=0 while num<10: print("Waiting for GREEN Signal") event.wait() print("GREEN Signal ... Traffic can move") while event.is_set(): num=num+1 print("Vehicle No:", num," Crossing the Signal") time.sleep(2) print("RED Signal ... Traffic has to wait") event=Event() t1=Thread(target=signal_state) t2=Thread(target=traffic_flow) t1.start() t2.start()

Output

Waiting for GREEN Signal
Traffic Police Giving GREEN Signal
GREEN Signal ... Traffic can move
Vehicle No: 1 Crossing the Signal
Vehicle No: 2 Crossing the Signal
Vehicle No: 3 Crossing the Signal
Vehicle No: 4 Crossing the Signal
Vehicle No: 5 Crossing the Signal
Signal is RED
RED Signal ... Traffic has to wait
Waiting for GREEN Signal
Traffic Police Giving GREEN Signal
GREEN Signal ... Traffic can move
Vehicle No: 6 Crossing the Signal
Vehicle No: 7 Crossing the Signal
Vehicle No: 8 Crossing the Signal
Vehicle No: 9 Crossing the Signal
Vehicle No: 10 Crossing the Signal

The Condition Object

Condition class in threading module class implements condition variable objects. Condition object forces one or more threads to wait until notified by another thread. Condition is associated with a Reentrant Lock. A condition object has acquire() and release() methods that call the corresponding methods of the associated lock.

threading.Condition(lock=None)

Following are the methods of the Condition object −

acquire(*args)

Acquire the underlying lock. This method calls the corresponding method on the underlying lock; the return value is whatever that method returns.

release()

Release the underlying lock. This method calls the corresponding method on the underlying lock; there is no return value.

wait(timeout=None)

This method releases the underlying lock, and then blocks until it is awakened by a notify() or notify_all() call for the same condition variable in another thread, or until the optional timeout occurs. Once awakened or timed out, it re-acquires the lock and returns.

wait_for(predicate, timeout=None)

This utility method may call wait() repeatedly until the predicate is satisfied, or until a timeout occurs. The return value is the last return value of the predicate and will evaluate to False if the method timed out.

notify(n=1)

This method wakes up at most n of the threads waiting for the condition variable; it is a no-op if no threads are waiting.

notify_all()

Wake up all threads waiting on this condition. This method acts like notify(), but wakes up all waiting threads instead of one. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised.

Example

In the following code, the thread t2 runs taskB() function and t1 runs taskA() function. The t1 thread acquires the condition and notifies it. By that time the t2 thread is in waiting state. After the condition is released, the waiting thread proceeds to consume the random number generated by the notifying function.

 
from threading import * import time import random numbers=[] def taskA(c): while True: c.acquire() num=random.randint(1,10) print("Generated random number:", num) numbers.append(num) print("Notification issued") c.notify() c.release() time.sleep(5) def taskB(c): while True: c.acquire() print("waiting for update") c.wait() print("Obtained random number", numbers.pop()) c.release() time.sleep(5) c=Condition() t1=Thread(target=taskB, args=(c,)) t2=Thread(target=taskA, args=(c,)) t1.start() t2.start()

When you execute this code, it will produce the following output −

waiting for update
Generated random number: 4
Notification issued
Obtained random number 4
waiting for update
Generated random number: 6
Notification issued
Obtained random number 6
waiting for update
Generated random number: 10
Notification issued
Obtained random number 10
waiting for update



The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.
Hasznosnak találta ezt a választ? 1 A felhasználók hasznosnak találták ezt (1 Szavazat)