如何停止多处理。进程

时间:2015-05-29 09:56:27

标签: python python-multiprocessing

我希望在一个进程中运行一些线程。主要过程应告诉该过程何时停止。我想知道以下代码是否是最好的方法。特别是,我认为行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()

1 个答案:

答案 0 :(得分:-1)

请完成 - reversed 多线程'池'需要在join()之前调用close()方法。 所以在代码中的stop()方法中 - 在pool.join()之前调用pool.close()应该可以解决问题。

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

如果您仍然遇到问题,请告诉我。

相关问题