Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import multiprocessing, random, time
- def multiprocessing_patch(self):
- # Including this function inside a class definition causes a recursion depth
- # exceeded error.
- key = object.__getattribute__(self, '_local__key')
- d = multiprocessing.current_process().__dict__.get(key)
- if d is None:
- d = {}
- multiprocessing.current_process().__dict__[key] = d
- object.__setattr__(self, '__dict__', d)
- # we have a new instance dict, so call out __init__ if we have
- # one
- cls = type(self)
- if cls.__init__ is not object.__init__:
- args, kw = object.__getattribute__(self, '_local__args')
- cls.__init__(self, *args, **kw)
- else:
- object.__setattr__(self, '__dict__', d)
- class MultiprocessingLocal(object):
- __slots__ = '_local__key', '_local__args', '_local__lock'
- def __new__(cls, *args, **kw):
- self = object.__new__(cls)
- key = '_local__key', 'multiprocessing_local.' + str(id(self))
- object.__setattr__(self, '_local__key', key)
- object.__setattr__(self, '_local__args', (args, kw))
- object.__setattr__(self, '_local__lock', multiprocessing.RLock())
- if args or kw and (cls.__init__ is object.__init__):
- raise TypeError("Initialization arguments are not supported")
- # We need to create the thread dict in anticipation of
- # __init__ being called, to make sure we don't call it
- # again ourselves.
- dict_ = object.__getattribute__(self, '__dict__')
- multiprocessing.current_process().__dict__[key] = dict_
- return self
- def __getattribute__(self, name):
- lock = object.__getattribute__(self, '_local__lock')
- lock.acquire()
- try:
- multiprocessing_patch(self)
- return object.__getattribute__(self, name)
- finally:
- lock.release()
- def __setattr__(self, name, value):
- lock = object.__getattribute__(self, '_local__lock')
- lock.acquire()
- try:
- multiprocessing_patch(self)
- return object.__setattr__(self, name, value)
- finally:
- lock.release()
- def __delattr__(self, name):
- lock = object.__getattribute__(self, '_local__lock')
- lock.acquire()
- try:
- multiprocessing_patch(self)
- return object.__delattr__(self, name)
- finally:
- lock.release()
- class Tester(MultiprocessingLocal):
- def __init__(self):
- self.pid = multiprocessing.current_process().ident
- self.random = random.random()
- def print_state(self):
- time.sleep(random.random()/10)
- print(self.pid, self.random)
- tester = Tester()
- tester.print_state()
- for _ in range(4):
- multiprocessing.Process(target=tester.print_state).start()
Add Comment
Please, Sign In to add comment