2015-05-29 124 views
2

我希望在进程中运行几个线程。主要过程应告诉该过程何时停止。我想知道下面的代码是否是最好的方式来做到这一点。特别是,我认为行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() 
+0

'Event'的wait()方法有什么问题?还要注意,'multiprocessing'进程可以拦截信号,也就是说你可以在子进程中处理SIGTERM并在管理进程中使用'p.terminate()'。 – dhke

+1

也许[Condition](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Condition)比'Event'更适合你。另外,如果将它们设置为'daemons',则不需要加入线程,一旦父进程退出,守护进程就会终止。 – sirfz

+0

什么都没有!那就是我正在寻找的东西。 – Baz

回答

-1

请通过 - https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.join 多线程 '池' 需要被调用的方法的close()之前加入()。 因此,在代码中的stop()方法中,在调用pool.join()之前调用pool.close()应该可以解决问题。

def stop(self): 
    self.finished = True 
    if self.is_alive(): 
     self.close() 
     self.join() 

请让我知道如果你仍然遇到问题。

+0

我没有使用multiprocessing.Pool – Baz