Created
July 30, 2014 07:49
-
-
Save cadl/093170b79d9071e59cb5 to your computer and use it in GitHub Desktop.
multiprocess decorator
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
import functools | |
from multiprocessing import Process, Manager | |
def multiprocess_run(process_num): | |
def returning_wrapper(func, index, return_dict, *args, **kwargs): | |
return_dict['proc'+str(index)] = func(*args, **kwargs) | |
def wrap(f): | |
return_dict = Manager().dict() | |
procs = [] | |
@functools.wraps(f) | |
def _wraped(*args, **kwargs): | |
for i in xrange(process_num): | |
proc = Process( | |
target=returning_wrapper, | |
args=tuple([f, i, return_dict] + list(args)), | |
kwargs=kwargs | |
) | |
procs.append(proc) | |
proc.start() | |
for proc in procs: | |
proc.join() | |
return dict(return_dict) | |
return _wraped | |
return wrap | |
if __name__ == '__main__': | |
@multiprocess_run(4) | |
def test(): | |
import time, random | |
t = random.choice(range(10)) | |
time.sleep(t) | |
return t | |
data = test() | |
print data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment