【问题标题】:How to stop a multiprocessing.Process如何停止 multiprocessing.Process
【发布时间】: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()

【问题讨论】:

  • Eventwait() 方法有什么问题?另请注意,multiprocessing 进程可以拦截信号,即您可以在子进程中处理 SIGTERM 并在管理器进程中使用 p.terminate()
  • 也许ConditionEvent 更适合你。另外,如果设置为daemons,则不需要加入线程,一旦父进程退出,守护进程将终止。
  • 没什么!这正是我想要的。

标签: python python-multiprocessing


【解决方案1】:

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

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

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

【讨论】:

  • 我没有使用 multiprocessing.Pool
猜你喜欢
  • 2020-03-19
  • 1970-01-01
  • 2022-08-16
  • 1970-01-01
  • 2018-06-21
  • 2020-07-05
  • 1970-01-01
  • 2019-12-23
  • 2020-09-17
相关资源
最近更新 更多