Python线程中断睡眠 [英] Python threading interrupt sleep
本文介绍了Python线程中断睡眠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Python中有没有办法在线程休眠时中断线程? (就像我们在Java中一样)
Is there a way in python to interrupt a thread when it's sleeping? (As we can do in java)
我正在寻找类似的东西.
I am looking for something like that.
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秒,如果我键入停止",则会中断
The thread is sleeping for 100 seconds and if I type 'stop', it interrupts
推荐答案
如何使用条件对象: https://docs.python.org/2/library/threading.html#condition-objects
使用wait( timeout )代替sleep().要中断",请调用notify().
Instead of sleep() you use wait(timeout). To "interrupt" you call notify().
这篇关于Python线程中断睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文