![]() |
VOOZH | about |
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:
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:-
Here we will take a simple example to explain how the above methods are used throughout the entire program:
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.