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

前端 未结 12 1639
野的像风
野的像风 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 08:00

    For anyone else who is seeking how to get a value from a Process using Queue:

    import multiprocessing
    
    ret = {'foo': False}
    
    def worker(queue):
        ret = queue.get()
        ret['foo'] = True
        queue.put(ret)
    
    if __name__ == '__main__':
        queue = multiprocessing.Queue()
        queue.put(ret)
        p = multiprocessing.Process(target=worker, args=(queue,))
        p.start()
        p.join()
        print(queue.get())  # Prints {"foo": True}
    

    Note that in Windows or Jupyter Notebook, with multithreading you have to save this as a file and execute the file. If you do it in a command prompt you will see an error like this:

     AttributeError: Can't get attribute 'worker' on 
    

提交回复
热议问题