Comment résoudre AttributeError lors de l'utilisation du multitraitement avec des fonctions personnalisées ?

Barbara Streisand
Libérer: 2024-10-17 19:45:02
original
256 Les gens l'ont consulté

How to Resolve AttributeError When Using Multiprocessing with Custom Functions?

Multiprocessing Issue: Resolving the AttributeError

When attempting to implement multiprocessing in code using the example provided in the official documentation, some users may encounter the following error:

AttributeError: can't get attribute 'f' on <module '__main__' (built-in)>
Copier après la connexion

This error stems from a design feature specific to multiprocessing.Pool, where it may encounter difficulties working with functions defined within the main Python script.

Solution:

To resolve this issue, it is necessary to separate the function definition into a separate file and import the module containing the function.

  1. Create a new file, e.g., defs.py, and define the function in that file:
<code class="python"># defs.py
def f(x):
    return x*x</code>
Copier après la connexion
  1. In the main script, import the module containing the function:
<code class="python"># run.py
from multiprocessing import Pool
import defs

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(defs.f, [1, 2, 3]))</code>
Copier après la connexion

Note:

If you had utilized a standard built-in function, such as print, instead of a user-defined function, the original example should have functioned properly. This indicates that the error arises from the design of multiprocessing.Pool in handling custom functions defined within the main script.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!