【问题标题】:Python multiprocessing: processes do not run in parallelPython多处理:进程不并行运行
【发布时间】:2023-09-12 00:10:02
【问题描述】:

我刚开始学习 python 中的多处理模块。我尝试运行以下简单代码:

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()

所以,我遇到了以下麻烦:我希望两个进程通过并行工作来打印立方体和正方形混合,比如

square of 0 is 0

cube of 0 is 0

square of 1 is 1

cube of 1 is 1

等等。我的脚本没有像描述的那样表现,而是打印:

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

很明显,进程不会并行运行,第二个进程只有在第一个进程完成后才会启动。

此外,当我运行类似代码但使用线程而不是进程时,它可以按我的意愿工作。

我使用的是 Windows 10 和 python 3.8。我将不胜感激有关如何解决此问题并使两个进程同时工作的任何信息,在此先感谢!

【问题讨论】:

    标签: python multithreading


    【解决方案1】:

    代码是正确的,它应该并行运行。这是我机器上的输出(linux mint + python3.8):

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

    也许有一些标准输出缓冲,打印调用发生在正确的时间,但流在最后被刷新,试试:

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

    sys.stdout.flush()
    

    【讨论】:

      最近更新 更多