在一定时间后停止线程

2024-04-28 06:31:46 发布

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

我希望在一定时间后终止一些线程。这些线程将运行一个无限的while循环,在这段时间内,它们可能会暂停一段随机的、大量的时间。线程的持续时间不能超过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

Tags: targetmaindef时间argssleep线程thread
3条回答

如果您希望线程在程序退出时停止(如示例所示),请将它们设为daemon threads

如果你想让你的线程在命令下死亡,那么你必须手工完成。有各种方法,但都需要检查线程的循环,看看是否该退出(参见Nix的示例)。

如果要使用类:

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

如果没有阻塞,这将起作用。

如果你正打算睡觉,那么你必须用这个事件来睡觉。如果你利用这个事件来睡觉,如果有人告诉你在“睡觉”时停下来,它就会醒过来。如果您使用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)

相关问题 更多 >