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

Mary-Kate Olsen
發布: 2024-10-17 19:48:30
原創
347 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!