Multiprocessing working in Python but not in iPython

前端 未结 2 1138
情书的邮戳
情书的邮戳 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

    0 讨论(0)
  • 2020-11-29 13:02

    From the documentation:

    Note

    Functionality within this package requires that the __main__ module be importable by the children. This is covered in Programming guidelines however it is worth pointing out here. This means that some examples, such as the multiprocessing.Pool examples will not work in the interactive interpreter

    0 讨论(0)
提交回复
热议问题