简体   繁体   中英

How to stop a multiprocessing.Process

I wish to run a few threads in a process. The main process shall tell this process when to stop. I am wondering if the following code is the nicest way to do this. In particular, I think the line while not self.event.is_set(): time.sleep(1) is weird but maybe its the best solution.

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()

Please go through - https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.join Multithreading 'pool' needs to be invoked the method close() before join(). So in the stop() methods in your code - invoking pool.close() before pool.join() should solve the problem.

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

Please let me know if still you are getting the problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM