Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiprocessing example giving AttributeError

I am trying to implement multiprocessing in my code, and so, I thought that I would start my learning with some examples. I used the first example found in this documentation.

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

When I run the above code I get an AttributeError: can't get attribute 'f' on <module '__main__' (built-in)>. I do not know why I am getting this error. I am also using Python 3.5 if that helps.

like image 889
PiccolMan Avatar asked Dec 29 '16 18:12

PiccolMan


People also ask

What is multiprocessing dummy?

dummy module module provides a wrapper for the multiprocessing module, except implemented using thread-based concurrency. It provides a drop-in replacement for multiprocessing, allowing a program that uses the multiprocessing API to switch to threads with a single change to import statements.

What is multiprocessing Threadpool?

A process pool object which controls a pool of worker processes to which jobs can be submitted. It supports asynchronous results with timeouts and callbacks and has a parallel map implementation. — multiprocessing — Process-based parallelism.

Can we use multiprocessing in Python?

Python's Global Interpreter Lock (GIL) only allows one thread to be run at a time under the interpreter, which means you can't enjoy the performance benefit of multithreading if the Python interpreter is required. This is what gives multiprocessing an upper hand over threading in Python.


1 Answers

This problem seems to be a design feature of multiprocessing.Pool. See https://bugs.python.org/issue25053. For some reason Pool does not always work with objects not defined in an imported module. So you have to write your function into a different file and import the module.

File: defs.py

def f(x):     return x*x 

File: run.py

from multiprocessing import Pool import defs   if __name__ == '__main__':     with Pool(5) as p:         print(p.map(defs.f, [1, 2, 3])) 

If you use print or a different built-in function, the example should work. If this is not a bug (according to the link), the given example is chosen badly.

like image 99
hr87 Avatar answered Sep 23 '22 12:09

hr87