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.
Asked
Active
Viewed 120 times
1
-
Have a look at the answer here: http://stackoverflow.com/a/11940400/369977 – pR0Ps Aug 27 '12 at 12:51
2 Answers
2
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()

Some programmer dude
- 400,186
- 35
- 402
- 621
-
How can this check be done dynamically, as an interrupt. Basically I will be creating a webpage where if a user presses a button it will send a HTTP GET to terminate all the threads of the second type. – Abhinav Aug 27 '12 at 13:25
-
1@sHoM Added a small example to hopefully give you an idea. – Some programmer dude Aug 27 '12 at 13:39
-
@sHoM Don't have to be, in that case you don't have to do the call to `join` and of course if your program exits there is no way for you to kill those threads. – Some programmer dude Aug 27 '12 at 14:44
-
I did the exact same thing as above but it does not leave the While loop but continues the same operations within the while. – Abhinav Aug 27 '12 at 14:53
1
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()

Charlie G
- 814
- 9
- 22
-
I need one function that will terminate them all no matter in which state they are. – Abhinav Aug 27 '12 at 13:23
-