Python多线程打印语句延迟到所有线程完成执行

时间:2013-08-14 14:27:38

标签: python multithreading

我在下面有一段代码可以创建一些线程来执行任务,它可以自行完成任务。但是我很难理解为什么我在函数中调用的print语句在所有线程完成并调用print 'finished'语句之后才会执行。我希望在线程执行时调用它们。有没有简单的方法来实现这一目标,为什么这首先以这种方式工作?

def func(param):
    time.sleep(.25)
    print param*2

if __name__ == '__main__':
    print 'starting execution'
    launchTime = time.clock()
    params = range(10)
    pool=multiprocessing.Pool(processes=100) #use N processes to download the data
    _=pool.map(func,params)
    print 'finished'

3 个答案:

答案 0 :(得分:15)

对于python 3 ,您现在可以像这样使用flush param:

print('Your text', flush=True)

答案 1 :(得分:12)

这是由于stdout缓冲造成的。你仍然可以刷新缓冲区:

import sys

print 'starting'
sys.stdout.flush()

您可以找到有关此问题的更多信息herehere

答案 2 :(得分:0)

围绕此问题和输出乱码(尤其是在Windows中为输出添加颜色时出现乱码..),我的解决方案是拥有一个消耗队列的专用打印线程

如果此 still 不起作用,请按照 @Or Duan

的建议,在您的打印声明中添加flush=True

另外,“最正确”的,但繁重的线程显示方法可能是使用logging

import threading
from queue import Queue

def display_worker(display_queue):
    while True:
        line = display_queue.get()
        if line is None:  # simple termination logic
            break
        print(line)


def some_other_worker(display_queue, other_args):
    # NOTE accepts queue reference as an argument, though it could be a global
    display_queue.put("something which should be printed from this thread")


def main():
    display_queue = Queue()  # synchronizes console output
    screen_printing_thread = threading.Thread(
        target=display_worker,
        args=(display_queue,),
    )
    screen_printing_thread.start()

    ### other logic ###

    display_queue.put(None)  # end screen_printing_thread
    screen_printing_thread.stop()
相关问题