プログラムの構造によっては、次のようなことを試してみてください。
import _thread
import sys
import time
def monitor(function):
def wrapper(*args, **kwargs):
sys.stdout.write('Starting ' + function.__name__ + '\n')
result = function(*args, **kwargs)
sys.stdout.write('Stopping ' + function.__name__ + '\n')
return result
return wrapper
@monitor
def main():
lock = _thread.allocate_lock()
lock.acquire()
_thread.start_new_thread(mainFoo, (lock,))
_thread.start_new_thread(monitorDisconnect, (lock,))
deadlock = _thread.allocate_lock()
_thread.start_new_thread(bunchOfOtherMonitors, (deadlock,))
with deadlock:
deadlock.acquire()
@monitor
def bunchOfFoos():
time.sleep(5)
@monitor
def mainFoo(lock):
try:
bunchOfFoos()
finally:
lock.release()
@monitor
def monitorDisconnect(lock):
with lock:
print('mainFoo has finished executing')
@monitor
def bunchOfOtherMonitors(deadlock):
time.sleep(10)
deadlock.release()
if __name__ == '__main__':
main()
threading
代わりに上位レベルのモジュールを使用すると、非常に似たようなことも実現できます。
from threading import *
import sys
import time
def monitor(function):
def wrapper(*args, **kwargs):
sys.stdout.write('Starting ' + function.__name__ + '\n')
result = function(*args, **kwargs)
sys.stdout.write('Stopping ' + function.__name__ + '\n')
return result
return wrapper
@monitor
def main():
main_foo = Thread(target=mainFoo)
monitor = Thread(target=monitorDisconnect, args=(main_foo,))
main_foo.start()
monitor.start()
other_monitors = Thread(target=bunchOfOtherMonitors)
other_monitors.start()
other_monitors.join()
@monitor
def bunchOfFoos():
time.sleep(5)
@monitor
def mainFoo():
bunchOfFoos()
@monitor
def monitorDisconnect(main_foo):
main_foo.join()
print('mainFoo has finished executing')
@monitor
def bunchOfOtherMonitors():
time.sleep(10)
if __name__ == '__main__':
main()