Python - 使用多处理时的多个输出副本

时间:2010-04-14 21:12:59

标签: python windows multiprocessing

  

可能重复:
  Multiprocessing launching too many instances of Python VM

模块通过python myscript.py运行(不是shell输入)

import uuid
import time
import multiprocessing


def sleep_then_write(content):
    time.sleep(5)
    print(content)

if __name__ == '__main__':
    for i in range(15):
        p = multiprocessing.Process(target=sleep_then_write,
                                    args=('Hello World',))
        p.start()

print('Ah, what a hard day of threading...')

此脚本输出以下内容:

Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
AAh, what a hard day of threading..
h, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

首先,为什么它会打印底部语句十六次(每个进程一次)而不是一次?

其次,请注意 AAh, h, 大约一半;那是真正的输出。这让我对现在使用线程持谨慎态度。

(Windows XP,Python 2.6.4,Core 2 Duo)

2 个答案:

答案 0 :(得分:4)

多处理通过启动多个进程来工作。每个进程都会加载一个脚本副本(这样它就可以访问“目标”函数),然后运行目标函数。

您获得16次底部打印声明,因为该声明独立于此并在您加载模块时打印。将它放在块中,它不会:

if __name__ == "__main__":
    print('Ah, what a hard day of threading...')

关于“AAh” - 你有多个进程,它们会在运行时产生输出,所以你只需从另一个进程旁边的一个进程获得“A”。

在处理多进程或多线程环境时,您必须考虑锁定和通信。这不是多处理所特有的;任何并发库都会遇到同样的问题。

答案 1 :(得分:2)

由于Windows缺少标准的fork系统调用,多处理模块在Windows上运行起来有点滑稽。首先,它为每个进程导入一次主模块(您的脚本)。有关详细说明,请参阅http://docs.python.org/library/multiprocessing.html#multiprocessing-programming

处的“Windows”字幕