Python线程中断睡眠

Pol*_*ist 3 python multithreading thread-sleep

python中有没有办法在线程休眠时中断线程?(就像我们在java中所做的那样)

我正在寻找类似的东西。

  import threading
  from time import sleep

  def f():
      print('started')
  try:
      sleep(100)
      print('finished')
  except SleepInterruptedException:
      print('interrupted')

t = threading.Thread(target=f)
t.start()

if input() == 'stop':
    t.interrupt()
Run Code Online (Sandbox Code Playgroud)

线程正在睡眠100秒,如果我键入“停止”,它将中断

He *_*ing 8

正确的方法是使用threading.Event。例如:

import threading

e = threading.Event()
e.wait(timeout=100)   # instead of time.sleep(100)
Run Code Online (Sandbox Code Playgroud)

在另一个线程中,您需要访问e。您可以通过发出以下命令中断睡眠:

e.set()
Run Code Online (Sandbox Code Playgroud)

这将立即中断睡眠。您可以检查的返回值e.wait以确定它是超时还是中断。有关更多信息,请参阅文档:https : //docs.python.org/3/library/threading.html#event-objects


Eir*_*k M 5

如何使用条件对象:https : //docs.python.org/2/library/threading.html#condition-objects

您使用 wait( timeout )代替 sleep( )。要“中断”,您可以调用 notify()。