我想在一个线程中运行一个进程(它在一个大型数据库表上迭代)。当线程运行时,我只想让程序等待。如果该线程花费的时间超过30秒,我想杀死该线程并执行其他操作。通过终止线程,我的意思是我希望它停止活动并优雅地释放资源。
我认为最好的方法是通过Thread()的join(delay)和is_alive()函数,以及一个Event。使用join(delay),我可以让我的程序等待30秒,让线程完成,通过使用is_alive()函数,我可以确定线程是否已经完成了它的工作。如果它还没有完成它的工作,就设置事件,线程知道在这一点上停止工作。
这种方法是有效的吗,这是我的问题陈述最典型的方式吗?
下面是一些示例代码:
import threading
import time
# The worker loops for about 1 minute adding numbers to a set
# unless the event is set, at which point it breaks the loop and terminates
def worker(e):
    data = set()
    for i in range(60):
        data.add(i)
        if not e.isSet():
            print "foo"
            time.sleep(1)
        else:
            print "bar"
            break
e = threading.Event()
t = threading.Thread(target=worker, args=(e,))
t.start()
# wait 30 seconds for the thread to finish its work
t.join(30)
if t.is_alive():
    print "thread is not done, setting event to kill thread."
    e.set()
else:
    print "thread has already finished."发布于 2019-12-11 14:59:20
我也在努力关闭一个等待接收通知的线程。尝试了user5737269在这里给出的解决方案,但它对我来说并不是真的有效。它在第二个join语句中卡住了(没有超时语句)。挣扎了很多,但没有找到任何解决这个问题的方法。经过思考后得到了这样的解决方案:我的线程正在等待接收que中的消息。如果在20秒内没有收到通知,我想关闭这个线程。所以,在20秒之后,我向这个que写了一条消息,这样线程就会自动终止。代码如下:
 q = Queue.Queue()
 t.join(20)
    if t.is_alive():
        print("STOPPING THIS THREAD ....")
        q.put("NO NOTIFICATION RECEIVED")
        t.join(20)
    else:
        print("Thread completed successfully!!")这对我很有效..希望这个想法能对某些人有所帮助!
https://stackoverflow.com/questions/34562473
复制相似问题