gpt4 book ai didi

Python 线程 - 在 join() 时做一些事情

转载 作者:行者123 更新时间:2023-11-28 22:36:27 27 4
gpt4 key购买 nike

python 2.6.6

我有一个要执行的线程列表,主代码将等待 (Threading.join()) 直到它们全部完成。

>>> for thread in threadList:
... thread.start()
>>> for t in threadList:
... t.join()

有没有一种方法可以在主代码等待线程结束时打印诸如“running...”之类的消息?

我想一秒接一秒地打印相同的东西(“正在运行...”),直到线程全部完成。

谢谢。


已解决

实现方案:

>>> for thread in threadList:
... thread.start()
>>> string = "running"
>>> while any(t.is_alive() for t in threadList):
... sys.stdout.write("\r%s" % string)
... sys.stdout.flush()
... string = string + "." #this may not be the best way
... time.sleep(0.5)

在我的例子中,“time.sleep(0.5)”的额外时间不是问题,尽管这不是最推荐的。

这会生成输出:

running........

“running”之后的点将在同一行上一个接一个地打印,同时有任何线程处于事件状态。完全符合我的预期!

基于@Manuel Jacob 和@Alex Hall 的回答。

最佳答案

Thread.join() 被设计成阻塞。您可以定期调用 Thread.is_alive(),而不是使用 Thread.join()。

你的例子改编:

for thread in threadList:
thread.start()
while any(thread.is_alive() for thread in threadList):
print('running...')
time.sleep(1)

正如评论中所指出的,当最后一个线程在休眠期间完成时,这可能会导致最多一秒的额外延迟。

关于Python 线程 - 在 join() 时做一些事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37421903/

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