簡體   English   中英

Python 在並行化任務中包含 while 循環

[英]Python include while loop inside parallelized task

我正在嘗試構建一個並行化任務,其中一組計算以不同的參數集並行發生。 然后在這些獨立任務中的每一個中,都有一些 while 循環,這些循環中的每一個都通過一系列參數運行。

每個並行化任務的結果都保存在 csv 文件中。 然而,while 循環似乎沒有進行每個並行化任務在 while 循環的第一次迭代時停止。

對此有什么可能的解釋嗎?

實際代碼在這里發布的方式很大,但抽象可能是這樣的:

def inner_func(a,b):
    while a<b:
        write_to_file(a)
        a++

if __name__ == '__main__':
    arguments=[(a,b),(b,c)]
    with multiprocessing.Pool(processes=6) as pool:
        pool.map(inner_func, arguments)

您提供的代碼包含錯誤,我已將其修復為:

import multiprocessing


def inner_func(input):
    a = input[0]
    while a < input[1]:
        print(a)
        a = a + 1


if __name__ == '__main__':
    arguments = [(1, 4), (5, 8)]

    with multiprocessing.Pool(processes=6) as pool:
        pool.map(inner_func, arguments)

執行導致:

結果

它解決了你的問題嗎?

我發現問題不在代碼中。 只是 Jupyter Notebook 出於某種原因在嘗試運行並行進程時必須將函數作為模塊導入,而不是在主要 function 所在的同一筆記本中定義它們。

暫無
暫無

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

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