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

Mary-Kate Olsen
Freigeben: 2024-10-17 19:48:30
Original
347 Leute haben es durchsucht

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>
Nach dem Login kopieren

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>
Nach dem Login kopieren

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>
Nach dem Login kopieren

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!

Quelle:php
Erklärung dieser Website
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
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!