Implement Inter Thread Communication with Event( ) Method in Python
Last Updated :
26 Nov, 2022
Here we will start from the basics of what inter-thread communication is? Inter Thread Communication is the process of communicating requirements between one to another thread. In simple words sometimes one thread may be required to communicate to another thread depending on the requirements. This is considered as Inter Thread Communication.
Event() Method: Here we talk about the Event() method, the Event object is considered or recommended as the simplest communication process or system between any threads. This system works on two conditions where the Event object is Enabled means set() or disabled means clear().
Syntax:
event_object = threading.Event()
In the Internally Event manages the process which will be worked internally and it can be Set (enabled) or Clear (disabled) using the methods on event objects. If the threads are to be Set then all the threads are going to be executed but if the threads are to be Clear then generally all the threads become to wait for execution.
Example :
We take an example to explain how the event method is used in the implementation of inter-thread communication:
Python3
#import modules
import threading
import time
if __name__ == '__main__':
# initializing the event object
event_object = threading.Event()
# defining task
def task():
print("\nStarted thread but waiting for event...")
event_set = event_object.wait(4)
if event_set:
print("\nreceived and releasing thread")
else:
print("\ntime is gone...")
# assigning task
thread1 = threading.Thread(target=task)
# starting thread
thread1.start()
time.sleep(3)
event_object.set()
print("\nsetting of event is done")
Output:

In the above following program in which we create the event object, and then we create a thread and start it, now the thread is set the event object with the set() method and in function task() where the thread is in waiting for the state if the event is set to the thread will execute here next instruction if it was not set then the program is terminated still there is having an instruction to be executed.
Here are some general methods are used in the Event class:-
- clear( ) Method: This method is fully opposite of the set() method, but this method also acts as a condition changer if the condition becomes False then which thread is not running or already in waiting, so they are still is in waiting for state and don't continue their execution.
- set( ) Method: In the set() method we used it as a condition changer between threads where if the condition will True then there are much thread which was in waiting for the state they become continue their execution.
- isSet( ) Method: This isSet() method has meaning as their name suggests is set, this method simplifies that the following event that we have created are set or not set.
- wait( time ) Method: To describe the wait() method in simple words we can say that thread waits until the execution of the set() method is not done. We can use time in it if we set a certain time then the execution will stop until time overs after that it will execute still the set() of an event is remaining.
Here we will take a simple example to explain how the above methods are used throughout the entire program:
Python3
# import time module
import time
# import threading module
import threading
class product:
def buyer(self):
print('John consumer is wait for product')
print('...............')
event_object.wait()
print('got product')
def seller(self):
time.sleep(5)
print('Tom producer producing items')
print('tom goes to retailer')
event_object.wait()
def retailer(self):
time.sleep(10)
print('retailer found that product and directly send to buyer')
event_object.set()
# class object
class_obj = product()
# setting event object
if __name__=='__main__':
event_object = threading.Event()
# creating threads
T1 = threading.Thread(target=class_obj.buyer)
T2 = threading.Thread(target=class_obj.seller)
T3 = threading.Thread(target=class_obj.retailer)
# starting threads
T1.start()
T2.start()
T3.start()
Output:

This is a simple example to explain the use of event() class and their methods in inter-thread communication. Here we use an example of buyer-seller and retailer, first, we have import two modules which are the threading module and time module, then we create a class product in which has the first function which is the buyer() which are having several instructions. At the first T3 thread will execute for retailer() function but the T3 is going to wait for 10sec because of the timer after this T2 is going to execute but same here T2 also have to wait for 5 sec, after that now T1 is going to execute for buyer() function in the buyer function when the wait() method is executed then thread T1 has to wait until an event is set(), Now T2 will execute their instructions where it has also wait() method when wait() is executed then thread T2 stops their execution until set() method called. Now it's time for thread T3 in this set() method is called which releases all the waiting thread from waiting for state and those threads like T2 and T1 continue their execution.
Similar Reads
Inter Thread Communication With Condition() Method in Python This article is based on how we use the Condition() method to implement Inter Thread Communication, let's discuss this topic below -: Let's have some brief discussion on Inter Thread Communication before talking about Condition() implementation for inter-thread communication, When any thread require
5 min read
Implementation of Queues in Multi-Threading in Python3 Implementation of Queues in Multi-Threading The Prerequisites Before reading this article, some important background reading is recommended to ensure that one is well equipped with the basic knowledge of threads as well as the basic knowledge of queues before trying to mix the two together. The offi
7 min read
Prevent Freezing in Python PYQT GUIs with QThread When performing long-running tasks, GUIs can become unresponsive or "freeze," frustrating users and making the application appear unprofessional. This is a common problem in applications built with PyQt, a set of Python bindings for the Qt application framework. To address this issue, PyQt provides
4 min read
How to run same function on multiple threads in Python? In a large real-world application, the modules and functions have to go through a lot of input and output-based tasks like reading or updating databases, communication with different micro-services, and request-response with clients or peers. These tasks may take a significant amount of time to comp
3 min read
Different way to create a thread in Python A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an Operating System. There are various ways to create a thread: 1) Create a Thread without using an Explicit function: By importing the module and creati
3 min read
How to create a new thread in Python Threads in python are an entity within a process that can be scheduled for execution. In simpler words, a thread is a computation process that is to be performed by a computer. It is a sequence of such instructions within a program that can be executed independently of other codes. In Python, there
2 min read
Handling a thread's exception in the caller thread in Python Multithreading in Python can be achieved by using the threading library. For invoking a thread, the caller thread creates a thread object and calls the start method on it. Once the join method is called, that initiates its execution and executes the run method of the class object. For Exception hand
3 min read
How does the Python Interpreter check thread duration? In Python, threads are a means of achieving concurrent execution. The Python interpreter employs a mechanism to manage and monitor the duration and execution of threads. Understanding how the Python interpreter handles thread duration is essential for developing efficient and responsive multithreade
3 min read
How to create telnet client with asyncio in Python Telnet is a client/server application protocol that uses TCP/IP for connection. Telnet protocol enables a user to log onto and use a remote computer as though they were connected directly to it within the local network. The system that is being used by the user for the connection is the client and t
4 min read
Python time.pthread_getcpuclockid() Function The pthread_getcpuclockid() function returns the clock id of the thread-specific CPU-time clock for the specified thread_id. The thread ids are obtained from the different threads that are running being used by that program. The thread ids can be obtained using the 'ident' field of the threading cla
2 min read