當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python Event clear()用法及代碼示例


Python Event.clear() 方法

clear() 是 Python 中線程模塊的 Event 類的內置方法。

當。。。的時候clear()方法被調用,該事件類對象的內部標誌被設置為 false。作為clear()方法被一個對象調用,所有調用 wait() 的線程都會阻塞,直到set()被調用以再次設置內部標誌為真。

模塊:

    from threading import Event

用法:

    clear()

參數:

  • None

返回值:

這個方法的返回類型是<class 'NoneType'>.該方法不返回任何內容。它隻將當前事件對象的內部標誌設置為 false。

例:

# 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")

輸出:

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


相關用法


注:本文由純淨天空篩選整理自 Python Event Class | clear() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。