Heim  >  Artikel  >  Backend-Entwicklung  >  Warum führt das Multiprocessing-Beispiel bei integrierten Funktionen zu „AttributeError“?

Warum führt das Multiprocessing-Beispiel bei integrierten Funktionen zu „AttributeError“?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-17 19:48:30348Durchsuche

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

Why Multiprocessing Example Gives AttributeError

In an attempt to delve into multiprocessing, an individual encountered an AttributeError while adapting the introductory example from the documentation:

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

The error: "AttributeError: can't get attribute 'f' on " perplexed the user.

To resolve this issue, it's important to understand that multiprocessing.Pool has a peculiar design feature. As noted in Python issue #25053, Pool sometimes falters when working with objects not defined in imported modules. As a workaround, you can define your function in a separate file and import the module.

Here's an example:

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>

This modification should resolve the AttributeError. However, it's worth noting that the given example in the documentation might not be the most suitable for beginners due to this potential issue.

Das obige ist der detaillierte Inhalt vonWarum führt das Multiprocessing-Beispiel bei integrierten Funktionen zu „AttributeError“?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn