当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。