【发布时间】:2015-05-29 09:56:26
【问题描述】:
我希望在一个进程中运行几个线程。主进程应该告诉这个进程什么时候停止。我想知道以下代码是否是最好的方法。特别是,我认为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()。 -
也许Condition 比
Event更适合你。另外,如果设置为daemons,则不需要加入线程,一旦父进程退出,守护进程将终止。 -
没什么!这正是我想要的。
标签: python python-multiprocessing