Python:在 while 循环中使用 join() 的线程
我希望 while 循环在 for 循环中创建的所有线程最多阻塞 5 秒。然而,下面的代码会被线程一一阻塞。我怎样才能实现我的目标?谢谢。
threads = []
while True:
for 3:
newThread = threading.Thread(..)
threads.append(newThread)
newThread.start()
newThread.join(5)
I would like my while loop to block at most 5 seconds for all threads it creates in the for loop. However, the following code will block by the threads one by one. How can I approach my goal? Thanks.
threads = []
while True:
for 3:
newThread = threading.Thread(..)
threads.append(newThread)
newThread.start()
newThread.join(5)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要使用条件变量(Python 中的
threading.Condition
)。它允许等待谓词变为真。在您的情况下,谓词是所有线程都已完成工作或超时
。下面的代码创建了 10 个线程,并等待它们以 5 秒的超时时间完成。详细日志将为您提供帮助:更多信息请访问 comp.programming.threads 常见问题解答。
You need to use condition variable (
threading.Condition
in Python). It allows to wait for a predicate to become true. In your case the predicate isall threads have finished work or time out exceeded
. Here is code which creates ten threads and waits until they are finished with 5sec time out. Verbose logs will help you:Further information at comp.programming.threads FAQ.
要做的一件事是启动所有线程,然后迭代数组并连接。但我想,这仍然会等待总共 5*线程计数秒。或者,您可以创建一个额外的线程,它只是无限期地等待您的线程。然后在你的主线程中你可以等待额外的线程 5 秒钟。
One thing to do is start all the threads, and then iterate over the array and join. But I suppose, this would still wait up to a total of 5*thread count seconds. Alternatively, you could create one additional thread that simply waits for your threads indefinitely. Then in your main thread you can just wait for the extra thread for 5 seconds.
您是否尝试每 5 秒生成一个线程,除非已经运行的线程之一结束,您希望更快地生成一个新线程?如果是这样,您可以使用
threading.Event
在工作线程结束时发出信号,并使用event.wait(timeout)
最多阻止该事件 5 秒:产量
Are you trying to spawn a thread every 5 seconds, except if one of the already-running threads ends, you wish to spawn a new thread sooner? If so, you could use a
threading.Event
to signal when a worker thread ends, and useevent.wait(timeout)
to block at most 5 seconds for the event:yields