python : To store the return value in a variable after multiprocessing of a function with a return value

Asked 2 years ago, Updated 2 years ago, 115 views

I wonder how I can save the return value of the executed function as a variable when I run a function with a return value as a multi-process.

You want to save and use the processed result as a variable after running as a multi-process, but if the process is active on the variable as shown below, the processed value is not substituted into the variable, but a process object is created.

In this situation, I wrote the question because I was wondering if the processed function values on the process could be used.

I looked for a related reference, but I'm not sure, so I'm asking.

from multiprocessing import Process

def func1(a,b):
   c = a+b
   return c

def func2(a,b):
       c = a-b
       return c

def func3(a,b):
    c = a*b
    return c



p1 = Process(target=func1, args(a,b)) 

p2 = Process(target=func2, args(a,b)) 

p3 = Process(target=func3, args(a,b)) 



p1.start()
p2.start()
p3.start()



p1.join()
p2.join()
p3.join()

python multiprocessing

2022-09-20 19:41

2 Answers

Unlike threads, processes are independent spaces. Process interprocess variables using shared memory. If you use Python's multiprocessing module, it hides all the troublesome tasks. Please refer to the example below to learn.

import multiprocessing

def worker(num):
    print(f'num: {num}')
    return num * 2

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes = 3)
    print(pool.map(worker, range(1, 6)))


2022-09-20 19:41

import multiprocessing

def worker(num, num2):
    print(f'num, num2: {num} {num2}')
    return num * num2

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes = 3)
    print(pool.starmap(worker, zip(range(1, 6), range(1, 6))))

num, num2: 3 3
num, num2: 1 1
num, num2: 2 2
num, num2: 5 5
num, num2: 4 4
[1, 4, 9, 16, 25]


2022-09-20 19:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.