作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有多个线程运行 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/
我是一名优秀的程序员,十分优秀!