Reputation:
I have two functions and I want to run them simultaneously. So, I tried:
from multiprocessing import Process
def func1():
for i in range(0, 100000000):
pass
return 'abc'
def func2():
for i in range(0, 100000000):
pass
return 'xyz'
if __name__=='__main__':
p1 = Process(target=func1()).start()
p2 = Process(target=func2()).start()
Now, how can I get return value of for example func1()
?
I can use for example print(func1())
to get returned value but it executes the function again and it takes a long time again to execute func1()
. How do I not cause the function to run again to get the result?
Upvotes: 1
Views: 2100
Reputation: 123393
Here's how it could be done using a multiprocessing.Pool
as I suggested in a comment.
import multiprocessing
def func1():
for i in range(0, 100000000):
pass
return 'abc'
def func2():
for i in range(0, 100000000):
pass
return 'xyz'
if __name__=='__main__':
funcs = func1, func2
with multiprocessing.Pool() as pool:
results = [pool.apply_async(func) for func in funcs]
pool.close()
pool.join()
results = [result.get() for result in results]
print(f'{results}') # -> ['abc', 'xyz']
Upvotes: 1
Reputation: 1359
you can also use the concurrent.futures
module
import concurrent.futures
_pool = concurrent.futures.ThreadPoolExecutor()
def func1():
for i in range(0, 100000000):
pass
return 'abc'
def func2():
for i in range(0, 100000000):
pass
return 'xyz'
if __name__=='__main__':
p1 = _pool.submit(func1)
p2 = _pool.submit(func2)
print(p1.result(), p2.result())
Upvotes: 0