How to Kill a Thread

How do you kill a Thread in Java?

See this thread by Sun on why they deprecated Thread.stop(). It goes into detail about why this was a bad method and what should be done to safely stop threads in general.

The way they recommend is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread terminate.

Is there any way to kill a Thread?

It is generally a bad pattern to kill a thread abruptly, in Python, and in any language. Think of the following cases:

  • the thread is holding a critical resource that must be closed properly
  • the thread has created several other threads that must be killed as well.

The nice way of handling this, if you can afford it (if you are managing your own threads), is to have an exit_request flag that each thread checks on a regular interval to see if it is time for it to exit.

For example:

import threading

class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""

def __init__(self, *args, **kwargs):
super(StoppableThread, self).__init__(*args, **kwargs)
self._stop_event = threading.Event()

def stop(self):
self._stop_event.set()

def stopped(self):
return self._stop_event.is_set()

In this code, you should call stop() on the thread when you want it to exit, and wait for the thread to exit properly using join(). The thread should check the stop flag at regular intervals.

There are cases, however, when you really need to kill a thread. An example is when you are wrapping an external library that is busy for long calls, and you want to interrupt it.

The following code allows (with some restrictions) to raise an Exception in a Python thread:

def _async_raise(tid, exctype):
'''Raises an exception in the threads with id tid'''
if not inspect.isclass(exctype):
raise TypeError("Only types can be raised (not instances)")
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid),
ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# "if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)
raise SystemError("PyThreadState_SetAsyncExc failed")

class ThreadWithExc(threading.Thread):
'''A thread class that supports raising an exception in the thread from
another thread.
'''
def _get_my_tid(self):
"""determines this (self's) thread id

CAREFUL: this function is executed in the context of the caller
thread, to get the identity of the thread represented by this
instance.
"""
if not self.isAlive():
raise threading.ThreadError("the thread is not active")

# do we have it cached?
if hasattr(self, "_thread_id"):
return self._thread_id

# no, look for it in the _active dict
for tid, tobj in threading._active.items():
if tobj is self:
self._thread_id = tid
return tid

# TODO: in python 2.6, there's a simpler way to do: self.ident

raise AssertionError("could not determine the thread's id")

def raiseExc(self, exctype):
"""Raises the given exception type in the context of this thread.

If the thread is busy in a system call (time.sleep(),
socket.accept(), ...), the exception is simply ignored.

If you are sure that your exception should terminate the thread,
one way to ensure that it works is:

t = ThreadWithExc( ... )
...
t.raiseExc( SomeException )
while t.isAlive():
time.sleep( 0.1 )
t.raiseExc( SomeException )

If the exception is to be caught by the thread, you need a way to
check that your thread has caught it.

CAREFUL: this function is executed in the context of the
caller thread, to raise an exception in the context of the
thread represented by this instance.
"""
_async_raise( self._get_my_tid(), exctype )

(Based on Killable Threads by Tomer Filiba. The quote about the return value of PyThreadState_SetAsyncExc appears to be from an old version of Python.)

As noted in the documentation, this is not a magic bullet because if the thread is busy outside the Python interpreter, it will not catch the interruption.

A good usage pattern of this code is to have the thread catch a specific exception and perform the cleanup. That way, you can interrupt a task and still have proper cleanup.

How can I kill a thread in python

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()

How to kill thread from inside another thread?

Here's how to use a shutdown flag:

thread_a_active = True

def functA():
print("functA started")
while thread_a_active:
time.sleep(1)

def functB(thread1):
print("functB started")
thread1.start()
x=0
while x<3:
x=x+1
time.sleep(1)
print(x)
print(threading.enumerate())
thread_a_active = False
while True:
#continue doing something....
pass

BTW, while and if statements in Python do not use outer parentheses. That's a bad habit carried over by C programmers.

How to kill a running thread in wait?

When i try to kill my Robber threads, some die , but some get stuck in the wait() block , what would be a better way to kill all the threads ,

The right way to "kill" a thread is to interrupt it with thread.interrupt(). If the thread is blocked in a wait(...) call, this will immediately throw InterruptedException. When you catch InterruptedException it is a good idea to immediately re-interrupt the thread to preserve the interrupt flag because when the exception is thrown, the interrupt bit is cleared.

try {
...wait();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
// handle the interrupt
return;
}

Since not all methods throw InterruptedException, you can also check to make sure the thread has been interrupted with something like the following:

if (Thread.currentThread().isInterrupted()) {
// stop processing
return;
}

Or in your case something like:

while (alive && !Thread.currentThread().isInterrupted()) {

Btw, alive should be volatile because it looks to be accessed by multiple threads.

How to kill a java thread?

Thread.interrupt() is the only safe method which is generally applicable. You can of course use other application-level signals (such as a conditional check on a volatile variable) to self-terminate. Other methods (such as all the deprecated Thread.xx methods) can pollute your application's state in non-deterministic ways, and would require reloading all application state.

How to kill a running thread?

You can use pthread_cancel() to kill a thread:

int pthread_cancel(pthread_t thread);

Note that the thread might not get a chance to do necessary cleanups, for example, release a lock, free memory and so on..So you should first use pthread_cleanup_push() to add cleanup functions that will be called when the thread is cancelled. From man pthread_cleanup_push(3):

These functions manipulate the calling thread's stack of
thread-cancellation clean-up handlers. A clean-up handler is a
function that is automatically executed when a thread is cancelled
(or
in various other circumstances described below); it might, for
example, unlock a mutex so that it becomes available to other threads
in the process.

Regarding the question of whether a thread will be cancelled if blocking or not, it's not guaranteed, note that the manual also mentions this:

A thread's cancellation type, determined by pthread_setcanceltype(3),
may be either asynchronous or deferred (the default for new
threads)
. Asynchronous cancelability means that the thread
can be canceled at any time (usually immediately, but the system does
not guarantee this
). Deferred cancelability means that cancellation
will be delayed until the thread next calls a function that is a
cancellation point.

So this means that the only guaranteed behaviour is the the thread will be cancelled at a certain point after the call to pthread_cancel().

Note:
If you cannot change the thread code to add the cleanup handlers, then your only other choice is to kill the thread with pthread_kill(), however this is a very bad way to do it for the aforementioned reasons.



Related Topics



Leave a reply



Submit