Python线程 - 在join()时执行某些操作

时间:2016-05-24 19:06:56

标签: python multithreading

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........

“run”之后的点将在同一行上一个接一个地打印,同时有任何线程处于活动状态。正如我预期的那样!

根据@Manuel Jacob和@Alex Hall的答案。

2 个答案:

答案 0 :(得分:3)

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)

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

答案 1 :(得分:0)

from time import sleep
from threading import Thread

threadList = [Thread(target=lambda: sleep(3)), Thread(target=lambda: sleep(5))]

for thread in threadList:
    thread.start()

def check_running():
    while True:
        alive = sum(thread.is_alive() for thread in threadList)
        if not alive:
            break
        print '%s threads still running...' % alive
        sleep(1)

Thread(target=check_running).start()

for t in threadList:
    t.join()

输出:

2 threads still running...
2 threads still running...
2 threads still running...
1 threads still running...
1 threads still running...

可替换地:

from time import sleep
from threading import Thread

threadList = [Thread(target=lambda: sleep(3), name='Alice'), Thread(target=lambda: sleep(5), name='Bob')]

for thread in threadList:
    thread.start()

for t in threadList:
    while True:
        t.join(timeout=1)
        if not t.is_alive():
            break
        print('%s is still running...' % t.name)

输出:

Alice is still running...
Alice is still running...
Bob is still running...