gpt4 book ai didi

python - python 如何在一定时间后终止线程?

转载 作者:行者123 更新时间:2023-12-01 04:14:21 27 4
gpt4 key购买 nike

我有多个线程运行 while 循环。我想在给定的时间后终止这些线程。我知道与此类似的其他问题,但我不知道如何将这些答案转移到我的代码中。

 def function1(arg1, arg2, arg3, duration):
t_end = time.time() + duration
while time.time() < t_end:
#do some stuff

for i in range(100):
t = Thread(target = function1, args=(arg1, arg2, arg3, 10))
t.start()

这会打开 100 个线程,但它们永远不会关闭。如何在指定时间(本例中为 10 秒)后关闭这些线程?我的函数打开一个套接字。

最佳答案

您可以将回调传递给每个线程。并创建一个线程列表。

threadlist  = {}
def cb(id, currtime):
t = threadlist[id]
d = currtime - t.starttime
if d > 10:
return True
else:
return False

def function1(arg1, arg2, arg3, duration, cb, threadid):
t_end = time.time() + duration
while time.time() < t_end:
#do some stuff
if cb(threadid, time.time()):
break

for i in range(100):
t = Thread(target = function1, args=(arg1, arg2, arg3, 10, cb, i))
threadlist[id] = {"starttime": time.time(), "thread": t}
t.start()

并检查:

time.sleep(15)
for item in threadlist.values():
print(item.thread.is_alive())

关于python - python 如何在一定时间后终止线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34503795/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com