How can I kill a thread in python
multithreading, python
Solution
If your thread is busy executing Python code, you have a bigger problem than the inability to kill it. The GIL will prevent any other thread from even running whatever instructions you would use to do the killing. (After a bit of research, I've learned that the interpreter periodically releases the GIL, so the preceding statement is bogus. The remaining comment stands, however.)
Your thread must be written in a cooperative manner. That is, it must periodically check in with a signalling object such as a semaphore, which the main thread can use to instruct the worker thread to voluntarily exit.
while not sema.acquire(False):
# Do a small portion of work…
or:
for item in work:
# Keep working…
# Somewhere deep in the bowels…
if sema.acquire(False):
thread.exit()
Problem
I start a thread using the following code. ``` t = thread.start_new_thread(myfunction) ``` How can I kill the thread `t` from another thread. So basically speaking in terms of code, I want to be able to do something like this. ``` t.kill() ``` Note that I'm using Python 2.4.