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


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


Python Event.is_set() 方法

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

一個事件類對象管理一個內部標誌,它的值可以被這個類的其他方法改變。is_set()如果事件對象的內部標誌為真,則函數返回真,否則返回假。

模塊:

    from threading import Event

用法:

    is_set()

參數:

  • None

返回值:

這個方法的返回類型是<class 'bool'>.如果當前事件類對象的內部標誌為真,則返回真,否則返回假。

例:

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

def helper_function(event_obj, timeout, i):
  # Thread has started, but it will wait 4 seconds 
  # for the event  
  print("Thread started, for the event to set")
  print("Is the event set to true now?", event_obj.is_set())

  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, 4, 30))
  thread1.start()
  # sleeping the current thread for 5 seconds
  time.sleep(5)
  
  # generating the event
  event_obj.set()
  print("Is the event set to true now?", event_obj.is_set())
  print("Event is set to true. Now threads can be released.")

輸出:

Thread started, for the event to set
Is the event set to true now? False
Time out occured, event internal flag still false. Executing thread without waiting for event
Value to be printed= 30
Is the event set to true now? True
Event is set to true. Now threads can be released.


相關用法


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