问题描述
似乎,如果您有一个n个线程的循环并以超时t一次将它们连接起来,则实际花费的时间为n * t,因为开始计数一个子线程的超时是最后一个线程的结束时间子线程.有什么办法可以将总时间减少到t not n * t?
It seems that if you have a loop of n threads and join them one by one with the timeout t, the actual time you take is n * t because the beginning to count timeout of one child thread is the ending time of last child thread. Is there any way to reduce this total time to t not n*t?
推荐答案
是的,您可以计算绝对超时,并在每次加入之前重新计算剩余的相对超时:
Yes, you can calculate an absolute timeout, and recompute your remaining relative timeout before every join:
# Join the_threads, waiting no more than some_relative_timeout to
# attempt to join all of them.
absolute_timeout = time.time() + some_relative_timeout
for thr in the_threads:
timeout = absolute_timeout - time.time()
if timeout < 0:
break
thr.join(timeout)
if thr.isAlive():
# we timed out
else:
# we didn't
现在,您是否*应该*这样做有点不透明.最好让守护程序"工作线程通过其他方式传达其完成情况:全局状态表,将完成"消息推送到队列等.
Now, whether or not you *should* do this is a bit opaque. It may be better to have "daemon" worker threads communicate their completion by other means: a global state table, pushes of "done" messages to a queue, etc.
这篇关于带有超时的python多线程连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!