How can I recover the return value of a function passed to multiprocessing.Process?

前端 未结 12 1642
野的像风
野的像风 2020-11-22 07:36

In the example code below, I\'d like to recover the return value of the function worker. How can I go about doing this? Where is this value stored?

12条回答
  •  一生所求
    2020-11-22 07:56

    I think the approach suggested by @sega_sai is the better one. But it really needs a code example, so here goes:

    import multiprocessing
    from os import getpid
    
    def worker(procnum):
        print('I am number %d in process %d' % (procnum, getpid()))
        return getpid()
    
    if __name__ == '__main__':
        pool = multiprocessing.Pool(processes = 3)
        print(pool.map(worker, range(5)))
    

    Which will print the return values:

    I am number 0 in process 19139
    I am number 1 in process 19138
    I am number 2 in process 19140
    I am number 3 in process 19139
    I am number 4 in process 19140
    [19139, 19138, 19140, 19139, 19140]
    

    If you are familiar with map (the Python 2 built-in) this should not be too challenging. Otherwise have a look at sega_Sai's link.

    Note how little code is needed. (Also note how processes are re-used).

提交回复
热议问题