Python:如何并行运行两个函数

时间:2014-11-25 18:10:44

标签: python function python-multithreading parallels python-multiprocessing

这是我的计划的结构:

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

我该如何做到这一点?

1 个答案:

答案 0 :(得分:3)

根据程序的结构,您可能想尝试这样的事情:

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