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

Python: How to run two functions in parallel

本问题已经有最佳答案,请猛点这里访问。

我的程序结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import _thread
import sys
import time

def monitor(function):
    def wrapper(*args, **kwargs):
        sys.stdout.write('Starting ' + function.__name__ + '
'
)
        result = function(*args, **kwargs)
        sys.stdout.write('Stopping ' + function.__name__ + '
'
)
        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模块,您也可以完成非常类似的工作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from threading import *
import sys
import time

def monitor(function):
    def wrapper(*args, **kwargs):
        sys.stdout.write('Starting ' + function.__name__ + '
'
)
        result = function(*args, **kwargs)
        sys.stdout.write('Stopping ' + function.__name__ + '
'
)
        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()