在一定时间后停止线程 [英] Stopping a thread after a certain amount of time
问题描述
我希望在一段时间后终止一些线程.这些线程将运行一个无限的 while 循环,在此期间它们可以随机停顿大量时间.线程的持续时间不能超过持续时间变量设置的时间.我怎样才能在持续时间设置的长度之后做到这一点,线程停止.
I'm looking to terminate some threads after a certain amount of time. These threads will be running an infinite while loop and during this time they can stall for a random, large amount of time. The thread cannot last longer than time set by the duration variable. How can I make it so after the length set by duration, the threads stop.
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
推荐答案
这将起作用如果您没有阻止.
This will work if you are not blocking.
如果您打算进行睡眠,则绝对必须使用该事件进行睡眠.如果你利用这个事件来睡觉,如果有人告诉你在睡觉"时停下来,它就会醒来.如果您使用 time.sleep()
,您的线程只会在 唤醒后停止.
If you are planing on doing sleeps, its absolutely imperative that you use the event to do the sleep. If you leverage the event to sleep, if someone tells you to stop while "sleeping" it will wake up. If you use time.sleep()
your thread will only stop after it wakes up.
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)
这篇关于在一定时间后停止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!