Python Event clear() Method with Example

Python Event.clear() Method: In this tutorial, we will learn about the clear() method of Event Class in Python with its usage, syntax, and examples. By Hritika Rajput Last updated : April 25, 2023

Python Event.clear() Method

The Event.clear() is an inbuilt method of the Event class of the threading module. When the clear() method is called, the internal flag of that event class object is set to false. As the clear() method gets called for an object, all the threads calling wait() will block until set() is called to set the internal flag true again.

Module

The following module is required to use clear() method:

import threading

Class

The following class is required to use clear() method:

from threading import Event

Syntax

The following is the syntax of clear() method:

clear()

Parameter(s)

The following are the parameter(s):

  • None

Return Value

The return type of this method is <class 'NoneType'>. The method does not return anything. It only sets the internal flag of the current event object to false.

Example of Event.clear() Method in Python

# Python program to explain the
# use of clear() method in Event() class
import threading
import time

def helper_function(event_obj, timeout, i):
  print("Thread started, and event is also set to true")
  # Sleeping for 8 second()
  time.sleep(8)
    
  flag = event_obj.wait(timeout)
  if flag:
    print("Event has set to true(), moving ahead with the thread")
  else:
    print("Time out occured, event internal flag still false. Executing thread without waiting for event")
    print("Value to be printed=", i)
    
if __name__ == '__main__':
  # Initialising an event object
  event_obj = threading.Event()
  
  # starting the thread who will wait for the event
  thread1 = threading.Thread(target=helper_function, args=(event_obj, 7, 30))
  # generating the event and setting to true
  event_obj.set()
  thread1.start()
  time.sleep(2)

  # Setting the event internal flag to false
  event_obj.clear()
  print("Event is set to false by clear() method")

Output

Thread started, and event is also set to true
Event is set to false by clear() method
Time out occured, event internal flag still false. Executing thread without waiting for event
Value to be printed= 30

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.