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


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


Python Event.wait() 方法

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

當我們想要一個線程等待一個事件時,我們可以在內部標誌設置為 false 的事件上調用 wait() 方法,從而阻塞線程,直到該事件對象的內部標誌被 set() 方法設置為 true。如果內部標誌在進入時為真,則線程不會被阻塞。線程保持阻塞狀態,直到內部標誌保持為 false 或發生超時。我們可以在 timeout 參數的幫助下為函數提供可選的超時。

模塊:

    from threading import Event

用法:

    wait(timeout=None)

參數:

  • timeout: 可選參數,指定wait()方法的超時時間。一旦超過該值,等待該事件的線程就會解除阻塞。其默認值為無。

返回值:

這個方法的返回類型是<class 'Bool'>.如果線程在超時之前被釋放,則返回,否則返回 false。

範例1:

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

def helper_function(event_obj, timeout,i):
  # Thread has started, but it will wait 10 seconds for the event  
  print("Thread started, for the event to set")
 
  flag = event_obj.wait(timeout)
  if flag:
    print("Event was set to true() earlier, 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,10,27))
  thread1.start()
  # sleeping the current thread for 5 seconds
  time.sleep(5)
  
  # generating the event
  event_obj.set()
  print("Event is set to true. Now threads can be released.")
  print()

輸出:

Thread started, for the event to set
Event is set to true. Now threads can be released.

Event was set to true() earlier, moving ahead with the thread

範例2:

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

def helper_function(event_obj, timeout,i):
  # Thread has started, but it will wait 3 seconds for the event  
  print("Thread started, for the event to set")
 
  flag = event_obj.wait(timeout)
  if flag:
    print("Event was set to true() earlier, 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,3,27))
  thread1.start()
  # sleeping the current thread for 5 seconds
  time.sleep(5)
  
  # generating the event
  event_obj.set()
  print("Event is set to true. Now threads can be released.")
  print()

輸出:

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


相關用法


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