Last active
September 24, 2015 14:30
-
-
Save lorn/c46749f573b24d14402e to your computer and use it in GitHub Desktop.
code from http://www.masnun.com/2014/01/01/async-execution-in-python-using-multiprocessing-pool.html
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
from multiprocessing import Pool | |
from time import sleep | |
from random import randint | |
import os | |
class AsyncFactory: | |
def __init__(self, num_procs,func, cb_func): | |
self.func = func | |
self.cb_func = cb_func | |
self.pool = Pool(processes=num_procs) | |
def call(self,*args, **kwargs): | |
self.pool.apply_async(self.func, args, kwargs, self.cb_func) | |
def wait(self): | |
self.pool.close() | |
self.pool.join() | |
@staticmethod | |
def cb_func(x): | |
print x |
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
from asyncfactory import AsyncFactory | |
def func(data): | |
#...do heavy stuff | |
return data | |
if __name__ == '__main__': | |
data = ".." | |
number_of_threads = 8 | |
async_work = AsyncFactory(number_of_threads, func, AsyncFactory.cb_func) | |
for item in data: | |
async_work.call(data) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment