Re: thread, threading; how to kill a thread?

From: Mustafa Demirhan (mustafademirhan_at_gmail.com)
Date: 11/19/04


Date: 18 Nov 2004 16:10:34 -0800

I had a very similar problem recently and I think finally found a
solution for that.

Let me first tell you that I needed this in a multi-threaded C++
program. Python is embedded into C++. I was able to kill the threads
using the TerminateThread API function of Windows; however this caused
GIL problems. The terminated thread doesn't release the GIL and all
other Python scripts running on different threads enter a deadlock.

So, I looked for a magical function that is called from a thread
(could be the main thread of the application) and this call will fail
another thread. In other words, lets say i have two threads: T1 and T2
- T1 wants to terminate T2. To achieve this, you should use the
PyThreadState_SetAsyncExc function.

In C++, my code is something like this (application specific parts of
the code it removed):

void SetAsyncExc (int nThreadId, PyThreadState * threadState)
{
        try
        {
                PyEval_AcquireLock ();
                PyThreadState_Swap (threadState);
                PyObject * exc = PyString_FromString ("Exit interrupt!");
                //PyObject * exc = PyErr_NewException ("TerminateThread", NULL,
NULL);
                
                int count = PyThreadState_SetAsyncExc (nThreadId, exc);
                if (count > 1) // we're in trouble!
                        PyThreadState_SetAsyncExc (nThreadId, NULL);
                
                Py_DECREF (exc);

                PyThreadState_Swap (NULL);
                PyEval_ReleaseLock ();
        }
        catch (...)
        {
#ifdef _DEBUG
                AfxMessageBox (_T ("Exception thrown in CPyManager::SetAsyncExc "));
#endif
        }
        return true;
}

You should be able to convert this code into a Python code easily. I
will leave that up to you ;)

nThreadId is the ID of the thread that you want to terminate (i.e.
thread id of T2). threadState is a pointer to the ThreadState
structure of thread that wants to terminate the target thread (i.e.
thread state of T1). Calling this function will cause an exception to
be thrown in T2 - Please note that i simply created a string as an
exception however instead of a string, a proper exception object
should be created. When the exception is thrown and caught in T2, T2
should simply exit.

I hope this helps.

Best wishes,
Mustafa Demirhan

Jerry Sievers <jerry@jerrysievers.com> wrote in message news:<m37jokwiqj.fsf@prod01.jerrysievers.com>...
> Greetings Pythonists;
>
> I have limited experience with threaded apps and plenty with old style
> forked heavyweight multi-processing apps.
>
> Using Python 2.3.3 on a Redhat 7.x machine.
>
> Wondering if there is a simple way from a main python program to kill
> a running thread? I see with the 'threading' module the way daemonic
> threads behave when the main program finishes.
>
> But suppose we have a simple thread running a function like;
>
> def timedLoop():
> while True:
> time.sleep(10)
> doSomething()
>
> All I am trying to do is stop that thread immediatly from the main
> program and it is unclear how to do this. I see that using
> del(threadObj) on the thread object that's running the loop function
> does nothing.
>
> Didn't notice anything obvious in the docs like a 'kill' method or
> similar. I don't necessarily want the main program to exit, just to
> kill one or more threads.
>
> Locks, conditions, semafores, signals?
>
> ARG! For heavens sake, what am I missing?
>
> Thanks



Relevant Pages

  • Re: How to kill Python interpreter from the command line?
    ... I am running Fedora Linux and KDE, using the Konsole command line. ... When coding Python, I regularly make a bug causing my program to not ... But how do I kill the non-terminating Python interpreter ... Neither do the "terminate ...
    (comp.lang.python)
  • Re: decorators tutorials
    ... I am learning python by learning django, ... allow the SystemExit exception to continue to propogate without doing ... # The func argument is a Pythong function object ... trying to get the result of DivXY, ...
    (comp.lang.python)
  • Re: math.nroot [was Re: A brief question.]
    ... >>> wish sometimes that Python would make up it's mind about what it does ... >> exception on overflow, invalid operation, and divide by 0, and "should ... >> not", by default, raise an exception on underflow or inexact. ... you can at least be pretty sure that an infinite result is the ...
    (comp.lang.python)
  • Re: exceptions
    ... How do younger languages like IO make this point more forcefully than lisp, ... deal with *all* errors in an interactive session, ... certainly in python ... > exception handling is hard-coded in syntax. ...
    (comp.lang.python)
  • Re: Detect End Process in application
    ... viruses that when you kill the process it starts right back up. ... So my previous answer "No it can't be done" might be wrong, all depends on why the user decides to use 'Taskman' to terminate an application, let me explain. ... The latter cannot be trapped, simply because no more user code will run in that process, the user portion of a process is cleaned up without returning a thread quantum to the process,. ...
    (microsoft.public.dotnet.languages.csharp)