Python Inter-Thread Communication
Explore how threads in Python can communicate with each other through shared memory using the threading
module. Learn about the Event
object, which manages an internal flag to facilitate communication between threads. Discover methods such as set()
, clear()
, wait()
, and is_set()
for controlling and checking the flag's state.
Python - Inter-Thread Communication
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 the 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: ReturnsTrue
if and only if the internal flag is true.set()
method: Sets the internal flag totrue
. All threads waiting for it to becometrue
are awakened. Threads that callwait()
once the flag istrue
will not block at all.clear()
method: Resets the internal flag tofalse
. Subsequently, threads callingwait()
will block untilset()
is called to set the internal flag totrue
again.wait(timeout=None)
method: Blocks until the internal flag istrue
. If the internal flag istrue
on entry, returns immediately. Otherwise, blocks until another thread callsset()
to set the flag totrue
, or until the optional timeout occurs.
Example
The following code simulates traffic flow being controlled by the state of a traffic signal, either GREEN or RED:
Code
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
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
The Condition
class in the threading
module implements condition variable objects. A condition object forces one or more threads to wait until notified by another thread. It is associated with a reentrant lock and has acquire()
and release()
methods that call the corresponding methods of the associated lock.
Constructor
threading.Condition(lock=None)
Methods of Condition object
acquire(*args)
: Acquires the underlying lock. This method calls the corresponding method on the underlying lock; the return value is whatever that method returns.release()
: Releases the underlying lock. This method calls the corresponding method on the underlying lock; there is no return value.wait(timeout=None)
: Releases the underlying lock, and then blocks until it is awakened by anotify()
ornotify_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 callwait()
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 toFalse
if the method timed out.notify(n=1)
: Wakes up at mostn
of the threads waiting for the condition variable; it is a no-op if no threads are waiting.notify_all()
: Wakes up all threads waiting on this condition. This method acts likenotify()
, but wakes up all waiting threads instead of one. If the calling thread has not acquired the lock when this method is called, aRuntimeError
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 a waiting state. After the condition is released, the waiting thread proceeds to consume the random number generated by the notifying function:
Code
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()
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