【发布时间】:2019-12-11 14:59:20
【问题描述】:
我想在一个线程中运行一个进程(它正在遍历一个大型数据库表)。当线程正在运行时,我只想让程序等待。如果该线程花费的时间超过 30 秒,我想终止该线程并执行其他操作。通过杀死线程,我的意思是我希望它停止活动并优雅地释放资源。
我认为最好的方法是通过Thread() 的join(delay) 和is_alive() 函数以及Event。使用join(delay) 我可以让我的程序等待30 秒等待线程完成,通过使用is_alive() 函数我可以确定线程是否已经完成它的工作。如果它还没有完成它的工作,则设置事件,并且线程知道此时停止工作。
这种方法是否有效,这是解决我的问题陈述的最 Pythonic 的方法吗?
这里是一些示例代码:
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."
【问题讨论】:
标签: python multithreading