Threading and GIL

Carl Banks pavlovevidence at gmail.com
Thu May 7 14:26:37 EDT 2009


On May 7, 12:20 am, googler.1.webmas... at spamgourmet.com wrote:
> thats the reason why its not working. Imagine the end() method of the
> thread object is called so the C++ Function is opened where the code
> for this method is in.

You're going to have to post some code if you want better help; this
description is unintelligible.  I don't know what you mean by end()
method, nor whether it's a Python method or C++ method, nor what
exactly you mean by thread object (C++ or Python object?) or C++
Function.


> At a line the Code ...->End() is called which waits that the C++
> Thread class
> is finished. BUT here is the problem: In the Method of the C++ class
> which is in threaded mode can't run because its still waiting that the
> GIL
> is released by the thread which executed the ->End() command.
>
> So the app has a deadlock when it arrives at       ->End() and
> PyGILState_Ensure
> function.

So you have to release the GIL before calling End().  Just surround End
() by Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.  (Presumably
you know the thread state when you call End(); if you don't then
surround the calls to Py_{BEGIN,END}_ALLOW_THREADS with calls to
PyGILState_{Ensure,Release}.  Yes, that means you acquire the GIL just
so you can be sure that you've released it.  I know of no other way to
be sure you don't have the GIL.)

If you are trying to kill a different thread, and I can't quite tell
if that's what you're doing, then be aware that it is very tricky to
do right and most think it to be a bad idea.  If you don't allow the
thread you're killing to clean up it can deadlock, and even if you do,
you have to be careful to clean up properly and you have to be
constantly on guard for what might happen in a thread is killed in the
middle of something.


Carl Banks



More information about the Python-list mailing list