Python - 使用多进程时输出多份复制
可能的重复问题:
多进程启动了太多Python虚拟机实例
这个模块是通过 python myscript.py
运行的(不是在命令行输入)
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 个回答
2
因为Windows系统没有标准的fork
这个系统调用,所以在Windows上使用多进程模块时会有点奇怪。具体来说,它会为每个进程都导入一次主模块(也就是你的脚本)。想了解更多详细信息,可以查看这个链接中的“Windows”部分。
4
多进程的工作原理是启动多个进程。每个进程都会加载你脚本的一个副本(这样它就能访问到“目标”函数),然后运行这个目标函数。
你会看到底部的打印语句出现16次,因为这个语句是单独放在那里的,当你加载模块时就会被打印出来。如果把它放在一个main块里,就不会这样了:
if __name__ == "__main__":
print('Ah, what a hard day of threading...')
关于“AAh”这个输出,你有多个进程在同时运行,它们会在运行时产生输出,所以你会看到一个进程的“A”和另一个进程的“Ah”挨在一起。
在处理多进程或多线程的环境时,你需要考虑锁定和通信的问题。这并不是多进程特有的;任何并发的库都会有类似的问题。