Last active
August 29, 2015 14:02
-
-
Save dmy3k/f81e3de5008b621d5819 to your computer and use it in GitHub Desktop.
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
""" | |
Execute function in process/thread pool with possibility to get return values | |
credits to http://stackoverflow.com/a/8533626 | |
""" | |
from multiprocessing.pool import ThreadPool as Pool | |
# for process-based pool use | |
# from multiprocessing import Pool | |
import time | |
def foo_pool(x): | |
time.sleep(2) | |
return x*x | |
result_list = [] | |
def log_result(result): | |
# This is called whenever foo_pool(i) returns a result. | |
# result_list is modified only by the main process, not the pool workers. | |
result_list.append(result) | |
def apply_async_with_callback(): | |
pool = Pool() | |
for i in range(10): | |
pool.apply_async(foo_pool, args = (i, ), callback = log_result) | |
pool.close() | |
pool.join() | |
print(result_list) | |
if __name__ == '__main__': | |
apply_async_with_callback() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment