How to store return value of function in multiprocessing process in python?

Viewed 5585

I am writing a python program which executes functions in parallel manner. Here is code:

from multiprocessing import Process

def sqr(args):
    results = []
    for i in args:
        results.append(i*i)
    return results

def cube(args):
    results = []
    for i in args:
        results.append(i*i*i)
    return results

def main():
    data = [1,2,3,4,5]
    p1 = Process(target=sqr, args=(data,))
    p1.start()
    p2 = Process(target=cube, args=(data,))
    p2.start()
    p1.join()
    p2.join()


main()

I don't have idea how can I get return values of sqr and cube functions.

I have tried this:

from multiprocessing import Process
from queue import Queue

def sqr(args, q):
    results = []
    for i in args:
        results.append(i*i)
    q.put(results)

def cube(args, q):
    results = []
    for i in args:
        results.append(i*i*i)
    q.put(results)

def main():
    q = Queue()
    data = [1,2,3,4,5]
    p1 = Process(target=sqr, args=(data, q))
    p1.start()
    p2 = Process(target=cube, args=(data, q))
    p2.start()
    p1.join()
    p2.join()
    print(q.get())

main()

This program will suspend for infinite time. I don't understand what's going wrong here? can anybody help me, how can I store return result of function? Any help would be appreciated.

3 Answers

You have three options to share resources between processes:

  1. File (e.g. pickle, cPickle, marshal, ...)
  2. Shared memory (e.g. queue)
  3. PIPE
Related