Skip to content

Instantly share code, notes, and snippets.

@dmy3k
Last active August 29, 2015 14:02
Show Gist options
  • Save dmy3k/f81e3de5008b621d5819 to your computer and use it in GitHub Desktop.
Save dmy3k/f81e3de5008b621d5819 to your computer and use it in GitHub Desktop.
"""
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