Abhinav
Abhinav

Reputation: 1042

How do I terminate selected threads

I have a code where in I have two types of threads. 3 threads are spawned from the second. I wanted to know if there is a function which I can call, which will terminate the three spawned threads of the second type but still keeping the first one running.

Upvotes: 1

Views: 131

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409432

A common solution is to have a global variable that the threads check if they should terminate or not.

Edit: An example of one way of doing it:

class MyThread(Thread):
    def __init__(self):
        self.keep_running = True

    def run(self):
        while self.keep_running:
            # Do stuff

my_thread = MyThread()
my_thread.start()

# Do some other stuff

my_thread.keep_running = False
my_thread.join()

Upvotes: 2

Charlie G
Charlie G

Reputation: 824

You can keep a thread pool for each type of thread and then terminate them accordingly. For instance, you can keep them in a Queue.Queue globally and then .stop() each as needed.

Edit// You can join every child thread you wish to stop to its parent with .join()

Upvotes: 1

Related Questions