简体   繁体   English

Python 多处理:进程不并行运行

[英]Python multiprocessing: processes do not run in parallel

Im new at learning a multiprocessing module in python.我刚开始学习 python 中的多处理模块。 I tried to run a following simple code:我尝试运行以下简单代码:

import multiprocessing, time

def print_squares(number):
    for i in range(number):
        print("square of {0} is {1}".format(i , i*i))
        time.sleep(0.1)

def print_cubes(number):
    for j in range(number):
        print("cube of {0} is {1}".format(j, j*j*j))
        time.sleep(0.1)

if __name__ == "__main__":
    process_1 = multiprocessing.Process(target = print_squares, args = (10,))
    process_2 = multiprocessing.Process(target = print_cubes, args = (10,))

    process_1.start()
    process_2.start()

    process_1.join()
    process_2.join()

So, I encountered a following trouble: I expected that two processes will print cubes and squares mixed, by working in parallel, like所以,我遇到了以下麻烦:我希望两个进程通过并行工作来打印混合的立方体和正方形,比如

square of 0 is 0

cube of 0 is 0

square of 1 is 1

cube of 1 is 1

and so on.等等。 Instead of behaving like described, my script prints:我的脚本没有像描述的那样表现,而是打印:

cube of 0 is 0
cube of 1 is 1
cube of 2 is 8
cube of 3 is 27
cube of 4 is 64
cube of 5 is 125
cube of 6 is 216
cube of 7 is 343
cube of 8 is 512
cube of 9 is 729
square of 0 is 0
square of 1 is 1
square of 2 is 4
square of 3 is 9
square of 4 is 16
square of 5 is 25
square of 6 is 36
square of 7 is 49
square of 8 is 64
square of 9 is 81

It is obvious that processes do not run in parallel, and second process starts only after first one has finished.很明显,进程不会并行运行,第二个进程只有在第一个进程完成后才会启动。

Also, when i run a similar code but using Threads instead of Processes, it works as I want.此外,当我运行类似的代码但使用线程而不是进程时,它可以按我的意愿工作。

Im using windows 10 and python 3.8.我正在使用 windows 10 和 python 3.8。 I will be grateful for any information how to solve this problem and make two processes work at the same time, thanks in advance!我将不胜感激有关如何解决此问题并使两个进程同时工作的任何信息,在此先感谢!

The code is correct, it should run in parallel.代码是正确的,它应该并行运行。 Here's the output on my machine (linux mint + python3.8):这是我机器上的 output(linux mint + python3.8):

square of 0 is 0
cube of 0 is 0
square of 1 is 1

Maybe there's some stdout buffering, and print calls happen at the right time, but the streams are flushed at the end, try:也许有一些标准输出缓冲,打印调用发生在正确的时间,但流在最后被刷新,试试:

print("cube of {0} is {1}".format(j, j * j * j), flush=True)

or或者

sys.stdout.flush()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM