Is there a way to kill a specific thread with Python? I have a thread running a function that is a loop and it is interfering with other parts of the program. I need to kill it when a certain function is started, is there a way to do this?
Asked
Active
Viewed 1,685 times
1
-
1If you have to *kill* a thread for your program to work correctly, you're doing something *very wrong*. – Jonathon Reinhart Aug 07 '12 at 21:40
-
Make the loop periodically check some boolean variable, let it be `proceed`. In main thread, set `proceed = False` when the other thread should stop; it will stop on next iteration. – 9000 Aug 07 '12 at 21:43
-
Can you describe the problem more? perhaps there's a better solution. I mean there's definitely a better solution than just killing the thread. But, perhaps you could use a threading.Lock() object to fix your issues – Ryan Haining Aug 07 '12 at 21:59
2 Answers
2
The best way to do this is to use an exit flag that the thread periodically checks, and exits if it is set. When you need to kill the thread, you would set this flag and wait for the thread to exit on its own.
This answer has additional information on why forcibly killing a thread is a bad idea, and a Python implementation for the above method.

Community
- 1
- 1

Andrew Clark
- 202,379
- 35
- 273
- 306
0
I found that if you define a Threading class with a self.flag
variable, and make the function you are calling a function of the class, you can then set the flag on a thread specific instance and exit specific threads with an if statement.
It's not hard to imagine this more dynamic and allowing for the ability to spawn and close threads.
class AutoPilotThreader(threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.flag = 0
def run(self):
print "Starting " + self.name
self.SelTestRun()
print "Exiting " + self.name
def SelTestRun(self):
# do code
while 1:
if self.flag:
return
else:
time.sleep(1)
my_threads = []
t1 = AutoPilotThreader(1, "t1")
t2 = AutoPilotThreader(2, "t2")
t1.start()
t2.start()
my_threads.append(t1)
my_threads.append(t2)
while 1:
print("What would you like to do: 1. Quit 2. Start New 3. Check")
choice = input("Enter : ")
if choice == 1:
choice = input(" 1 or 2 or 3 ")
if choice == 1:
t1.flag = 1
elif choice ==2:
t2.flag = 1
elif choice ==3:
t3.flag = 1 .........

Chris W
- 49
- 1
- 5