Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MultiProcessing in python3 not working

I am using multi processing in python3 for first time. Here is what I am trying to implement :

import concurrent
t = concurrent.futures.ProcessPoolExecutor(4)
g = t.map(lambda x:10*x, range(10))

And it is throwing errors:

File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/queues.py", line 242, in _feed
    obj = ForkingPickler.dumps(obj)
  File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/multiprocessing/reduction.py", line 50, in dumps
    cls(buf, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <function <lambda> at 0x102f03730>: attribute lookup <lambda> on __main__ failed

and hangs out every time.

like image 666
pg2455 Avatar asked Oct 20 '25 05:10

pg2455


1 Answers

The function passed to t.map needs to be picklable. Anonymous functions (i.e. lambda functions) are not picklable -- at least not by default. To fix, define the function in the global namespace:

import concurrent.futures as CF
def func(x):
    return 10*x

if __name__ == '__main__':
    with CF.ProcessPoolExecutor(4) as t:
        g = t.map(func, range(10))
        print(list(g))
        # [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
like image 137
unutbu Avatar answered Oct 21 '25 19:10

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!