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