I'm trying to learn the multiprocessing module and decorators. I have two questions about the code below:
from time import sleep
from multiprocessing import Process
class async:
def __init__(self, function):
self.func = function
def __call__(self, *args, **kwargs):
p = Process(target = self.func, args = args, kwargs = kwargs)
p.start()
@async
def printA():
sleep(1)
print("A")
def main():
printA()
printA()
printA()
#do more work
if __name__ == "__main__":
main()
Right now I'm getting
PicklingError: Can't pickle <function printA at 0x00000273F97FF1E0>: it's not the same object as __main__.printA
I'm not sure how to fix this. I feel like this was working on my work unix machine, is it a Windows thing?I want the child Processes to self terminate upon completion. I tried wrapping the function with
sys.exit()
at the end, and using that as the target for the Process, butsys.exit()
doesn't seem to properly terminate the zombie processes. What would be the correct way?
I don't want to do a blocking join()
, nor set daemon=True
. The end goal would be someone could import this module, put @async on any function, and it would run in a separate process and then terminate itself when it reaches the end of the function.