Multiprocessing working in Python but not in iPython

前端 未结 2 1156
情书的邮戳
情书的邮戳 2020-11-29 11:58

I am running the following code in iPython:

import multiprocessing

def my_function(x):
    \"\"\"The function you want to compute in parallel.\"\"\"
    x +         


        
2条回答
  •  一个人的身影
    2020-11-29 12:40

    At least in the current version of Jupyter Notebook (the successor of IPython) you can solve this by moving the target function to a separate module, and importing it.

    I have no idea why this works, it's rather odd, but it does.

    i.e. - in a workers.py file put

    def my_function(x):
        """The function you want to compute in parallel."""
        x += 1
        return x
    

    Then in IPython/Jupyter notebook put:

    import multiprocessing
    import workers
    
    pool = multiprocessing.Pool()
    results = pool.map(workers.my_function, [1,2,3,4,5,6])
    print(results)
    

    also - the if-main thingy doesn't seem to be needed.

    Credit: Gaurav Singhal

提交回复
热议问题