Skip to content

Instantly share code, notes, and snippets.

@kemingy
Last active January 21, 2021 13:01
Show Gist options
  • Save kemingy/419fc5a0d6c176db69f27f701f1ba507 to your computer and use it in GitHub Desktop.
Save kemingy/419fc5a0d6c176db69f27f701f1ba507 to your computer and use it in GitHub Desktop.
fork will share the current state, spawn will reimport and rebuild everything
import os
import multiprocessing as mp
data = {
"msg": "hello world",
}
class Demo:
def __repr__(self):
return f"<{self.__class__.__name__}>"
def foo(obj):
print(os.getpid(), obj)
def bar(cls):
print(os.getpid(), cls())
demo = Demo()
def patch_cls():
Demo.__repr__ = lambda _: "<>"
def patch_instance():
demo.__repr__ = lambda _: "<>"
def patch():
data["local"] = "patch"
if __name__ == "__main__":
ctx = mp.get_context("fork")
# ctx = mp.get_context("spawn")
patch()
print(data)
p = ctx.Process(target=foo, args=(data,))
p.start()
p.join()
patch_cls()
print(Demo())
p = ctx.Process(target=bar, args=(Demo,))
p.start()
p.join()
patch_instance()
print(demo)
p = ctx.Process(target=foo, args=(demo,))
p.start()
p.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment