Python-启动和停止多个线程
我有三个函数,函数A,函数B和函数C。Python-启动和停止多个线程,python,multithreading,function,conditional-statements,simultaneous,Python,Multithreading,Function,Conditional Statements,Simultaneous,我有三个函数,函数A,函数B和函数C。 我希望functionA和functionB同时运行,当functionB中的条件变为true时,我希望functionA停止,functionC运行,然后functionA与functionB一起再次开始运行 所以基本上,functionA看起来像: def functionA: while True: if condition == true: functionB.stop()
我希望functionA和functionB同时运行,当functionB中的条件变为true时,我希望functionA停止,functionC运行,然后functionA与functionB一起再次开始运行 所以基本上,functionA看起来像:
def functionA:
while True:
if condition == true:
functionB.stop()
functionC()
有人能帮我吗?
感谢有了并行编程,做事总是有多种方法的。所以其他人可能对如何做到这一点有完全不同的想法 首先想到的是via。保留其中三个,并根据需要打开/关闭它们
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()
未经测试的代码比较粗糙,而且比需要的更详细(您可以使用一个workerdef
编写所有这些代码,该workerdef
包含一些额外的参数),但希望能够让您走上正确的道路