fork(1) download
  1. import gc
  2. import multiprocessing
  3.  
  4. class Cycle(object):
  5. def __init__(self):
  6. self.g = self.gen()
  7. next(self.g)
  8. def gen(self):
  9. try:
  10. yield self
  11. finally:
  12. print('Doing one-time cleanup')
  13.  
  14. def work():
  15. # Pretend this does work that triggers a collection cycle
  16. gc.collect()
  17.  
  18. # Get some allocations done now that would have triggered an
  19. # inconvenient collection if we did them later
  20. p = multiprocessing.Process(target=work)
  21. p.start()
  22. p.join()
  23.  
  24. print('Creating cyclic trash')
  25. Cycle()
  26.  
  27. try:
  28. p = multiprocessing.Process(target=work)
  29. p.start()
  30. p.join()
  31.  
  32. work()
  33.  
  34. print('Oops, did cleanup twice')
  35. finally:
  36. print('Doing other one-time cleanup')
  37.  
  38. print("*Didn't* do the other cleanup twice, even though we forked to run p")
Success #stdin #stdout 0.07s 10344KB
stdin
Standard input is empty
stdout
Creating cyclic trash
Doing one-time cleanup
Doing one-time cleanup
Oops, did cleanup twice
Doing other one-time cleanup
*Didn't* do the other cleanup twice, even though we forked to run p