编程语言
首页 > 编程语言> > python-使用多处理的流程没有输出

python-使用多处理的流程没有输出

作者:互联网

我是多处理的初学者,谁能告诉我为什么它不产生任何输出?

import multiprocessing

def worker(num):
    """thread worker function"""

    print('Worker:', num)

if __name__ == '__main__':
    jobs = []

    for i in range(4):
        p = multiprocessing.Process(target=worker, args=(i,))
        jobs.append(p)
        p.start()

解决方法:

您正在启动Process(),但从不等待其完成,因此程序的执行在后台进程完成之前结束.尝试此操作,并致电Process.join()

import multiprocessing
import sys

def worker(num):
    """thread worker function"""

    print('Worker:', num)
    sys.stdout.flush()

if __name__ == '__main__':
    jobs = []

    for i in range(4):
        p = multiprocessing.Process(target=worker, args=(i,))
        jobs.append(p)
        p.start()

    map(lambda p: p.join(), jobs)

在这里,我们使用map()在作业列表中的每个进程上调用join().

这是此工作的示例:

In [127]: %paste
import multiprocessing
import sys

def worker(num):
    """thread worker function"""

    print('Worker:', num)
    sys.stdout.flush()

if __name__ == '__main__':
    jobs = []

    for i in range(4):
        p = multiprocessing.Process(target=worker, args=(i,))
        jobs.append(p)
        p.start()

    map(lambda p: p.join(), jobs)

## -- End pasted text --
Worker: 2
Worker: 1
Worker: 0
Worker: 3

In [128]:

至于为什么它在IDLE中不起作用,请参见this answer

However, to see the print output, at least on Windows, one must start IDLE from a console like so.

06002

(Use idlelib.idle on 2.x.) The reason is that IDLE runs user code in a separate process. Currently the connection between the IDLE process and the user code process is via a socket. The fork done by multiprocessing does not duplicate or inherit the socket connection. When IDLE is started via an icon or Explorer (in Windows), there is nowhere for the print output to go. When started from a console with python (rather than pythonw), output goes to the console, as above.

标签:python-idle,python-3-x,multiprocessing,python,python-multiprocessing
来源: https://codeday.me/bug/20191118/2029248.html