首頁  >  文章  >  後端開發  >  為什麼使用內建函數的多重處理範例會導致“AttributeError”?

為什麼使用內建函數的多重處理範例會導致“AttributeError”?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-17 19:48:30348瀏覽

Why Does Multiprocessing Example Result in 'AttributeError' with Built-in Functions?

為什麼多重處理範例給出AttributeError

在嘗試深入研究多重處理時,有人在改編文件中的介紹性範例時遇到了AttributeError:

<code class="python">from multiprocessing import Pool
def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))</code>

錯誤:「AttributeError:無法在上取得屬性'f'>」讓使用者感到困惑。

要解決此問題,重要的是要了解 multiprocessing.Pool 具有獨特的設計功能。如 Python 問題 #25053 所述,在處理匯入模組中未定義的物件時,Pool 有時會出現問題。作為解決方法,您可以在單獨的檔案中定義函數並匯入模組。

以下範例:

defs.py:

<code class="python">def f(x):
    return x*x</code>

run.py:

<code class="python">from multiprocessing import Pool
import defs

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(defs.f, [1, 2, 3]))</code>

run.py:

此修改應該可以解決AttributeError。然而,值得注意的是,由於這個潛在的問題,文件中給出的範例可能並不最適合初學者。

以上是為什麼使用內建函數的多重處理範例會導致“AttributeError”?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn