Created
April 26, 2018 13:32
-
-
Save benjbaron/02787b155f951fcaa6c3b52d160bd8ae to your computer and use it in GitHub Desktop.
Use the `multiprocessing` lbrary to run two processes `f1` and `f2` in parallel and get their respective outputs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from multiprocessing import Pool | |
# can also work with ThreadPool, by importing | |
# from multiprocessing.dummy import Pool | |
def f1(a,b): | |
print("run f1(%s,%s)" % (a,b)) | |
time.sleep(2) | |
print("end f1") | |
return a*b | |
def f2(a,b): | |
print("run f2(%s,%s)" % (a,b)) | |
time.sleep(3) | |
print("end f2") | |
return a+b | |
if __name__ == '__main__': | |
p = Pool(10) | |
res_f1 = p.apply_async(f1, args=(5,4)) | |
res_f2 = p.apply_async(f2, args=(5,4)) | |
p.close() | |
p.join() | |
print(res_f1.get(), res_f2.get()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment