【问题标题】:Stopping a thread after a certain amount of time一定时间后停止线程
【发布时间】:2011-09-25 08:25:49
【问题描述】:

我希望在一定时间后终止一些线程。这些线程将运行一个无限的while循环,在此期间它们可能会随机停顿很长时间。线程的持续时间不能超过持续时间变量设置的时间。 在持续时间设置的长度之后,我怎样才能做到这一点,线程停止。

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

【问题讨论】:

  • 你的线程会被阻塞吗?
  • 线程将无限循环运行。线程有可能会随机休眠一段时间。线程绝对不能在程序开始时指定的持续时间内运行。如果线程不知道他们花了多少时间睡觉,他们怎么知道什么时候结束。
  • 是否有人可以回答他的问题,而不要求他将整个世界都倾斜到它的轴上。还有其他像我这样的程序员需要这个问题的答案,他们绝对肯定不能以任何其他方式(目前)。

标签: python multithreading


【解决方案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()

【讨论】:

    【解决方案2】:

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

    如果您打算进行睡眠,则绝对必须使用该事件进行睡眠。如果你利用这个事件来睡觉,如果有人告诉你在“睡觉”时停下来,它就会醒来。如果您使用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)
    

    【讨论】:

    • stop_event.wait(time) 中的 time 应该是像 1 这样的数字变量,还是像 import time 中的 time 模块?使用这样的模块似乎很奇怪,所以我只是在检查。
    • 在谷歌上找到这个并且有同样的问题所以决定我会贡献。这是几分之一秒。所以stop_event.wait(1) 是 1 秒。
    • 这是一个完美问题的完美答案。两者都非常简洁、可访问和可概括,但它们都传达了相当大的复杂性。干得好。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多