在一定时间后停止线程
我想在一段时间后结束一些线程。这些线程会一直在一个无限循环中运行,而在这个过程中,它们可能会随机停顿很长时间。线程的运行时间不能超过我设置的一个叫做“duration”的变量所规定的时间。
我该怎么做才能让这些线程在达到“duration”设定的时间后停止呢?
def main():
t1 = threading.Thread(target=thread1, args=1)
t2 = threading.Thread(target=thread2, args=2)
time.sleep(duration)
#the threads must be terminated after this sleep
4 个回答
1
如果你想使用一个类:
from datetime import datetime,timedelta
class MyThread():
def __init__(self, name, timeLimit):
self.name = name
self.timeLimit = timeLimit
def run(self):
# get the start time
startTime = datetime.now()
while True:
# stop if the time limit is reached :
if((datetime.now()-startTime)>self.timeLimit):
break
print('A')
mt = MyThread('aThread',timedelta(microseconds=20000))
mt.run()
11
如果你希望在程序退出时线程也能停止(就像你例子中提到的那样),那么你需要把它们设置为守护线程。
如果你想要手动让线程停止,那就得自己来处理。虽然有几种方法,但都需要在线程的循环中检查一下,看看是不是该退出了(可以参考Nix的例子)。
108
这个方法会有效果,前提是 你没有阻塞。
如果你打算让程序“睡觉”,那么一定要通过事件来实现这个“睡觉”。如果你利用事件来让程序“睡觉”,那么当有人告诉你停止的时候,它会立刻醒来。如果你用 time.sleep()
,你的线程只会在“睡觉”结束后才会停止。
import threading
import time
duration = 2
def main():
t1_stop = threading.Event()
t1 = threading.Thread(target=thread1, args=(1, t1_stop))
t2_stop = threading.Event()
t2 = threading.Thread(target=thread2, args=(2, t2_stop))
time.sleep(duration)
# stops thread t2
t2_stop.set()
def thread1(arg1, stop_event):
while not stop_event.is_set():
stop_event.wait(timeout=5)
def thread2(arg1, stop_event):
while not stop_event.is_set():
stop_event.wait(timeout=5)