Implement Inter Thread Communication with Event( ) Method in Python

02 Feb, 2021
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 modulesimport threadingimport time  if __name__ == '__main__':      # initializing the event object    event_object = threading.Event()  # defining taskdef 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 taskthread1 = threading.Thread(target=task)  # starting threadthread1.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 there 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 moduleimport time  # import threading moduleimport 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 objectif __name__=='__main__':  event_object = threading.Event()  # creating  threadsT1 = threading.Thread(target=class_obj.buyer)T2 = threading.Thread(target=class_obj.seller)T3 = threading.Thread(target=class_obj.retailer)  # starting threadsT1.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.
Python-threading
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.