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”,它将中断
正确的方法是使用
threading.Event
。例如:在另一个线程中,您需要有权访问
e
。您可以通过发出以下命令来中断睡眠:这会立即中断睡眠。您可以检查
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()。
相关问题 更多 >
编程相关推荐