我希望在一个进程中运行几个线程。主进程将告诉这个进程何时停止。我想知道以下代码是否是最好的方法。尤其是,我认为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()
。 - dhkeEvent
更适合您。此外,如果将线程设置为daemons
,则无需加入这些线程,一旦父进程退出,守护进程将终止。 - sirfz