Python线程中断睡眠

2024-04-26 04:40:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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()

线程正在休眠100秒,如果我键入“stop”,它将中断


Tags: 方法fromimporttimedefsleepjavastop
2条回答

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

import threading

e = threading.Event()
e.wait(timeout=100)   # instead of time.sleep(100)

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

e.set()

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

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

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

相关问题 更多 >