I just tried to apply multiprocessing to a loop that was written as list comprehension, as described here: How to parallelize list-comprehension calculations in Python?
The preliminaries work as they should:
>>> import multiprocessing
>>> try:
... cpus = multiprocessing.cpu_count()
... except NotImplementedError:
... cpus = 2 # arbitrary default
...
>>>
>>> def square(n):
... return n * n
...
>>> pool = multiprocessing.Pool(processes=cpus)
>>> cpus
12
Then, just to check, I'm not misunderstanding how map()
works:
>>> map(square, range(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
So, that would all look reasonable so far. But when I execute the line given by Mahmoud in the accepted answer linked above:
>>> print pool.map(square, range(10))
Process PoolWorker-1:
Process PoolWorker-2:
Process PoolWorker-12:
Process PoolWorker-6:
Process PoolWorker-9:
Process PoolWorker-4:
Process PoolWorker-8:
Process PoolWorker-10:
Process PoolWorker-11:
Traceback (most recent call last):
File "C:\Program Files\WinPython-64bit-2.7.6.3\python-2.7.6.amd64\lib\multiprocessing\process.py", line 258, in _bootstrap
self.run()
File "C:\Program Files\WinPython-64bit-2.7.6.3\python-2.7.6.amd64\lib\multiprocessing\process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "C:\Program Files\WinPython-64bit-2.7.6.3\python-2.7.6.amd64\lib\multiprocessing\pool.py", line 102, in worker
task = get()
File "C:\Program Files\WinPython-64bit-2.7.6.3\python-2.7.6.amd64\lib\multiprocessing\queues.py", line 376, in get
return recv()
AttributeError: 'module' object has no attribute 'square'
Process PoolWorker-5:
...and this takes the entire console with it.
I've no idea why this would not work, and it seems like a very easy simple example, and 'square' is indeed defined and works, as the test with map()
shows. Am I overlooking something so obvious that others don't even mention it? Or something version-specific?
I'm using Python 2.7.6 (Winpython 64, to be precise) on Windows 7 professional, and this happens in Spyder and in the stand-alone Python console.