Python Forum
Terminating Subprocesses and Threads while they're calculating
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Terminating Subprocesses and Threads while they're calculating
#5
(Oct-17-2020, 06:04 AM)Gribouillis Wrote: There are still things to try. You could call queue.close() and queue.join_thread() in the worker process when it receives the instruction to stop. This would wait until every data previously sent to the queue has been written in the underlying pipe. Also it would raise an exception if the run() function still tries to put() anything else in the queue.

This solution works
from multiprocessing import Process, Lock
from threading import Thread
from time import sleep
from sys import exit
from multiprocessing import Queue


class Worker(Process):

    def __init__(self, queue: Queue):
        Process.__init__(self)
        self.queue = queue

    def run(self):
        i = 0
        try:
            while True:
                self.queue.put(i)
                i += 1
        except ValueError:
            pass

    def stop(self):
        self.queue.put("END")
        self.queue.close()
        self.queue.join_thread()
        self.terminate()


class Listener(Thread):

    def __init__(self):
        Thread.__init__(self)
        self.queue = Queue()
        self.worker = Worker(self.queue)
        self.is_running = True

    def run(self):
        self.worker.start()
        while self.is_running:
            try:
                data = self.queue.get()
                if data != "END":
                    pass
                else:
                    self.is_running = False
            except TypeError:
                self.is_running = False

    def stop(self):
        self.worker.stop()
        self.is_running = False


class System:

    def __init__(self):
        self.listener = Listener()

    def start(self):
        self.listener.start()

    def stop(self):
        self.listener.stop()


if __name__ == "__main__":
    system = System()
    system.start()
    sleep(0.1)
    system.stop()
    sleep(1)
    print(f"Process Alive: {system.listener.worker.is_alive()}")
    print(f"Thread Alive: {system.listener.is_alive()}")
Reply


Messages In This Thread
RE: Terminating Subprocesses and Threads while they're calculating - by lvlanson - Oct-17-2020, 12:33 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Subprocesses not opening File Select Dialog teut 2 2,570 Feb-22-2021, 08:07 PM
Last Post: teut
Question Terminating threads Gilush 1 2,039 Jun-09-2020, 09:57 AM
Last Post: Gribouillis
  Using Terminating Signal to Terminate Long Threads crcali 1 2,727 Apr-06-2018, 01:26 AM
Last Post: woooee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020