我希望在进程中运行几个线程。主要过程应告诉该过程何时停止。我想知道下面的代码是否是最好的方式来做到这一点。特别是,我认为行while not self.event.is_set(): time.sleep(1)
是奇怪的,但也许它是最好的解决方案。如何停止多处理。进程
import threading
import multiprocessing
import time
class T(threading.Thread):
def __init__(self):
super(T, self).__init__()
self.finished = False
def run(self):
while not self.finished:
print("*")
time.sleep(1)
def stop(self):
self.finished = True
if self.is_alive(): self.join()
class P(multiprocessing.Process):
def __init__(self):
super(P, self).__init__()
self.event = multiprocessing.Event()
self.t1 = T()
self.t2 = T()
def run(self):
self.t1.start()
self.t2.start()
while not self.event.is_set(): time.sleep(1)
self.t1.stop()
self.t2.stop()
def stop(self):
self.event.set()
self.join()
p = P()
try:
p.start()
time.sleep(3)
finally:
p.stop()
'Event'的wait()方法有什么问题?还要注意,'multiprocessing'进程可以拦截信号,也就是说你可以在子进程中处理SIGTERM并在管理进程中使用'p.terminate()'。 – dhke
也许[Condition](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Condition)比'Event'更适合你。另外,如果将它们设置为'daemons',则不需要加入线程,一旦父进程退出,守护进程就会终止。 – sirfz
什么都没有!那就是我正在寻找的东西。 – Baz