Created
July 25, 2016 22:34
-
-
Save danodonovan/ab9e0d3ba387523431cc09c8ae485dbb to your computer and use it in GitHub Desktop.
Call a non-static function on a class in parallel.
This file contains hidden or 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 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