Sunday 20 December 2015

Python: Threading: Event objects

Event object is used for inter thread communication. Every event object maintains a flag that can be set to true with the set() method and reset to false with the clear() method. ‘wait’ method blocks until the flag is true.

threading.Event
threading module provides Event class to define Event objects. Every Event object maintains a flag internally, by default flag is set to true.

Following are the methods provided by Event object.
Method
Description
is_set()
Returns True if the flag is set to True, else False.
set()
Sets the flag to true. All the threads that are waiting for flag to set true are awakened. Threads that call wait() once the flag is true will not block at all.
clear()
Reset the flag to false. Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again.
wait(timeout=None)
Block until the internal flag is true or until the optional timeout occurs. ‘timeout’ is a floating point number specifying a timeout for the operation in seconds.


MyThread.py
import threading
import time

class MyThread(threading.Thread):
 global event
 
 def run(self):
  name = threading.current_thread().getName()
  if(name=="publisher"):
   print(name, " publishng the event")
   event.set()
  else:
   print(name, " Waiting for the event from publisher")
   event.wait()
   print(name, " Received event from publisher")
   
 
global event
event = threading.Event()
 
thread1 = MyThread(name="publisher")

thread2 = MyThread(name="subscriber_1")
thread3 = MyThread(name="subscriber_2")
thread4 = MyThread(name="subscriber_3")
thread5 = MyThread(name="subscriber_4")


thread2.start()
thread3.start()
thread4.start()
thread5.start()
time.sleep(3)
thread1.start()

$ python3 MyThread.py 
subscriber_1  Waiting for the event from publisher
subscriber_2  Waiting for the event from publisher
subscriber_3  Waiting for the event from publisher
subscriber_4  Waiting for the event from publisher
publisher  publishng the event
subscriber_1  Received event from publisher
subscriber_2  Received event from publisher
subscriber_3  Received event from publisher
subscriber_4  Received event from publisher



Previous                                                 Next                                                 Home

No comments:

Post a Comment