简体   繁体   中英

Python multiprocessing: processes do not run in parallel

Im new at learning a multiprocessing module in 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. 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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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