Skip to content

Instantly share code, notes, and snippets.

@internetimagery
Last active June 28, 2022 09:24
Show Gist options
  • Save internetimagery/38073f88e89d809dc918791666edabc9 to your computer and use it in GitHub Desktop.
Save internetimagery/38073f88e89d809dc918791666edabc9 to your computer and use it in GitHub Desktop.
Register Process on multiprocessing.manager class
# Permission to use, copy, modify, and/or distribute this software for any purpose with or without
# fee is hereby granted.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
# THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
# AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# Access to Process from multiprocessing managers
from multiprocessing import Process
from multiprocessing.managers import NamespaceProxy
class ProcessProxy(NamespaceProxy):
_exposed_ = NamespaceProxy._exposed_ + (
"close",
"is_alive",
"join",
"kill",
"start",
"terminate",
)
def close(self):
return object.__getattribute__(self, "_callmethod")("close")
def is_alive(self):
return object.__getattribute__(self, "_callmethod")("is_alive")
def join(self, timeout=None):
return object.__getattribute__(self, "_callmethod")("join", (timeout,))
def kill(self):
return object.__getattribute__(self, "_callmethod")("kill")
def start(self):
return object.__getattribute__(self, "_callmethod")("start")
def terminate(self):
return object.__getattribute__(self, "_callmethod")("terminate")
def register_process(manager_cls):
"""
Register the ability for the provided manager to create process objects
"""
manager_cls.register("Process", Process, ProcessProxy)
# DEMO ##############
from multiprocessing import current_process
from multiprocessing.managers import BaseManager
register_process(BaseManager)
def say_hi(num):
proc = current_process()
for i in range(num):
print("HI!", i, proc, proc.pid)
if __name__ == "__main__":
man = BaseManager()
man.start()
proc = man.Process(target=say_hi, args=(5,))
proc.start()
print(proc, proc.pid)
proc.join(timeout=3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment