一定时间后停止线程 [英] Stopping a thread after a certain amount of time

查看:83
本文介绍了一定时间后停止线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在一段时间后终止某些线程.这些线程将运行一个无限的while循环,在这段时间内,它们可能会停顿一段随机的大量时间.线程的持续时间不能超过duration变量设置的时间. 在持续时间设置的长度之后,如何使线程停止.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆