thread, threading; how to kill a thread?

Mustafa Demirhan mustafademirhan at gmail.com
Thu Nov 18 19:10:34 EST 2004


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 at jerrysievers.com> wrote in message news:<m37jokwiqj.fsf at 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



More information about the Python-list mailing list