Skip to content

Instantly share code, notes, and snippets.

@danodonovan
Created July 25, 2016 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danodonovan/ab9e0d3ba387523431cc09c8ae485dbb to your computer and use it in GitHub Desktop.
Save danodonovan/ab9e0d3ba387523431cc09c8ae485dbb to your computer and use it in GitHub Desktop.
Call a non-static function on a class in parallel.
from multiprocessing import Pool
from multiprocessing.pool import ApplyResult
def call_it(instance, name, args=(), kwargs=None):
if kwargs is None:
kwargs = {}
return getattr(instance, name)(*args, **kwargs)
class Test(object):
def __init__(self, count):
self.count = count
def do_work(self, start):
return list(range(start, start + self.count))
if __name__ == '__main__':
t = Test(3)
pool = Pool(4)
async_results = [
pool.apply_async(call_it,
args = (t, 'do_work', (i,))) for i in range(4)
]
#async_results = [pool.apply_async(t.do_work, (i,)) for i in range(4)]
pool.close()
# waiting for all results
map(ApplyResult.wait, async_results)
lst_results=[r.get() for r in async_results]
print(lst_results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment