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

Mary-Kate Olsen
Release: 2024-10-17 19:48:30
Original
348 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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.

The above is the detailed content of Why Does Multiprocessing Example Result in \'AttributeError\' with Built-in Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!