1

Here's the structure of my program:

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

How can I accomplish this?

0

1 Answer 1

4

Depending on the structure of your program, you might want to try something like this:

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()

You can also accomplish something very similar if you use the higher level threading module instead:

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()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.