簡體   English   中英

Python 多處理:進程不並行運行

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

我剛開始學習 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。 我將不勝感激有關如何解決此問題並使兩個進程同時工作的任何信息,在此先感謝!

代碼是正確的,它應該並行運行。 這是我機器上的 output(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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM