Python - 启动和停止多个线程

时间:2014-05-04 16:38:43

标签: python multithreading function conditional-statements simultaneous

我有三个函数,functionA,functionB和functionC。
我希望functionA和functionB同时运行,当functionB中的条件变为true时,我希望functionA停止,functionC运行,然后functionA再次开始运行,与functionB一起。

基本上,functionA看起来像是:

def functionA:
    while True:
        if condition == true:
            functionB.stop()
            functionC()

任何人都可以帮我吗? 感谢

1 个答案:

答案 0 :(得分:2)

通过并行编程,总有不止一种方法可以做。所以其他人可能对如何做到这一点有完全不同的想法。

首先想到的方法是通过Event。保持其中三个,并根据需要打开/关闭它们。

from threading import Thread, Event

def worker1(events):
    a,b,c = events
    while True:
        a.wait() # sleep here if 'a' event is set, otherwise continue

        # do work here

        if some_condition:
            c.clear() # put c to sleep
            b.set() # wake up, b    

def worker2(events):
    a,b,c = events
    while True:
        b.wait() 
        #do work
        if some_condition:
            a.clear()
            c.set()

def worker3(events):
    a,b,c = events
    while True:
        c.wait() 
        #do work
        if some_condition:
            b.clear()
            a.set()

然后启动它们:

events = [Event() for _ in range(3)]
events[0].set()
events[1].set()
#events[2] starts un-set, i.e. worker3 sleeps at start

threads = []
threads.append(Thread(target=worker1, args=(events,)))
threads.append(Thread(target=worker2, args=(events,)))
threads.append(Thread(target=worker3, args=(events,)))

for t in threads:
    t.start()
for t in threads:
    t.join()

粗糙的未经测试的代码,并且比它需要的更冗长(你可以用一个带有一些额外参数的工人def来编写这一切),但是应该希望让你走上正确的道路。