python - Opposite of __init__ in thread class -
i understand __init__() called automatically when create class newthread = mythread(property)
, run() triggered newthread.start()
. looking called automatically before thread terminates, don't have explicitly call self.cleanup()
before each return statement.
class mythread(thread): def __init__(self, property): thread.__init__(self) self.property = property def cleanup(self): # clean here def run(self): # stuff self.cleanup() # current work around return
one way making thread
subclass context manager. make __exit__()
special method want triggered.
the following shows i'm proposing. note: renamed property
argument passing constructor because property
name of python built-in.
from threading import thread import time test_thread_exception = false # change desired class mythread(thread): def __init__(self, attribute): thread.__init__(self) self.attribute = attribute def cleanup(self): # clean here print(' cleaning after thread') def run(self): if test_thread_exception: raise runtimeerror('oops!') # force exception print(' other thread running...') time.sleep(2) # something... def __enter__(self): try: self.run() except exception exc: print('error: {} exception raised thread'.format(exc)) raise # reraise exception return self def __exit__(self, *args): self.cleanup() print('main thread begins execution') mythread('hello') thread: print('doing other things in main thread while other thread running') print('main thread continuing...')
output:
main thread begins execution other thread running... doing other things in main thread while other thread running cleaning after thread main thread continuing on...
if change test_thread_exception
true
, cleanup()
won't called since thread didn't run successfully—although change if wished, may need ensure doesn't called twice. here's code above in case:
main thread begins execution error: oops! exception raised thread traceback (most recent call last): file "opposite_init.py", line 37, in <module> mythread('hello') thread: file "opposite_init.py", line 27, in __enter__ self.run() file "opposite_init.py", line 21, in run raise runtimeerror('oops!') # force exception runtimeerror: oops!
Comments
Post a Comment