import gc
import multiprocessing
class Cycle( object ) :
def __init__ ( self ) :
self .g = self .gen ( )
next( self .g )
def gen( self ) :
try :
yield self
finally :
print ( 'Doing one-time cleanup' )
def work( ) :
# Pretend this does work that triggers a collection cycle
gc .collect ( )
# Get some allocations done now that would have triggered an
# inconvenient collection if we did them later
p = multiprocessing.Process ( target= work)
p.start ( )
p.join ( )
print ( 'Creating cyclic trash' )
Cycle( )
try :
p = multiprocessing.Process ( target= work)
p.start ( )
p.join ( )
work( )
print ( 'Oops, did cleanup twice' )
finally :
print ( 'Doing other one-time cleanup' )
print ( "*Didn't* do the other cleanup twice, even though we forked to run p" )
aW1wb3J0IGdjCmltcG9ydCBtdWx0aXByb2Nlc3NpbmcKCmNsYXNzIEN5Y2xlKG9iamVjdCk6CglkZWYgX19pbml0X18oc2VsZik6CgkJc2VsZi5nID0gc2VsZi5nZW4oKQoJCW5leHQoc2VsZi5nKQoJZGVmIGdlbihzZWxmKToKCQl0cnk6CgkJCXlpZWxkIHNlbGYKCQlmaW5hbGx5OgoJCQlwcmludCgnRG9pbmcgb25lLXRpbWUgY2xlYW51cCcpCgpkZWYgd29yaygpOgoJIyBQcmV0ZW5kIHRoaXMgZG9lcyB3b3JrIHRoYXQgdHJpZ2dlcnMgYSBjb2xsZWN0aW9uIGN5Y2xlCglnYy5jb2xsZWN0KCkKCiMgR2V0IHNvbWUgYWxsb2NhdGlvbnMgZG9uZSBub3cgdGhhdCB3b3VsZCBoYXZlIHRyaWdnZXJlZCBhbgojIGluY29udmVuaWVudCBjb2xsZWN0aW9uIGlmIHdlIGRpZCB0aGVtIGxhdGVyCnAgPSBtdWx0aXByb2Nlc3NpbmcuUHJvY2Vzcyh0YXJnZXQ9d29yaykKcC5zdGFydCgpCnAuam9pbigpCgpwcmludCgnQ3JlYXRpbmcgY3ljbGljIHRyYXNoJykKQ3ljbGUoKQoKdHJ5OgoJcCA9IG11bHRpcHJvY2Vzc2luZy5Qcm9jZXNzKHRhcmdldD13b3JrKQoJcC5zdGFydCgpCglwLmpvaW4oKQoKCXdvcmsoKQoKCXByaW50KCdPb3BzLCBkaWQgY2xlYW51cCB0d2ljZScpCmZpbmFsbHk6CglwcmludCgnRG9pbmcgb3RoZXIgb25lLXRpbWUgY2xlYW51cCcpCgpwcmludCgiKkRpZG4ndCogZG8gdGhlIG90aGVyIGNsZWFudXAgdHdpY2UsIGV2ZW4gdGhvdWdoIHdlIGZvcmtlZCB0byBydW4gcCIp