1

これが私のプログラムの構造です:

def bunchOfFoos()

...

...

def mainFoo():
    #calls a bunch of functions

def monitorDisconnect():
    #this function should run in parallel with mainFoo() and monitor for any disconnect. If a disconnect is detected, it'll call mainFoo() again

def bunchOfOtherMonitors():
    #functions monitoring for other things in parallel

どうすればこれを達成できますか?

4

1 に答える 1

4

プログラムの構造によっては、次のようなことを試してみてください。

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()
于 2014-11-25T18:50:46.983 に答える