Understanding PyEval_InitThreads

hg hansgeunsmeyer at earthlink.net
Wed Nov 20 21:44:56 EST 2002


Thomas Heller <theller at python.net> wrote in message news:<7kf83526.fsf at python.net>...

> Unfortunately it won't work this way.
> 
> Think of call_some_c_code() being the C standard library's qsort
> function, and call_back_into_python() is the function pointer I gave
> qsort to do the comparison. There's no way to pass the thread state to
> the callback function!

I'm not sure if I understand you, but what you're saying doesn't make
sense to me. The call_back_into_python is called by call_some_c_code,
so if you pass a pointer to the current thread state as arg, you could
also pass it on to call_back_into_python, couldn't you? It doesn't
matter whether or not call_back_into_python itself is passed as an
argument to call_some_c_code.

Another moment to pass on a pointer to the current thread state would
be when you register the Python object that will actually be called by
your callback.
I assume here that your call_back_into_python is intended to wrap a
call to
PyObject_CallObject.  If so, you have to pass it a pointer to some
callable Python object, so I assume you have some function to register
which object will actually be called by your call_back_into_python. 
So, at the moment when you register this Python function, you could
also save and/or pass on a pointer to the current thread state. No?

> 
> Storing the thread state in a global variable would be possible, but
> in this case it wouldn't be thread safe, I assume, and *only* work if
> the callout into C is done by my extension module.

I see no reason why this wouldn't be thread-safe. You could store the
current thread state when you initialize your module.

As far as I understand it, it doesn't really matter _what_ the thread
state is that you swap into the current state before you do the
callback, as long as it is _some_ valid thread state (not NULL). So,
before you do the callback, at any moment when you're in the main
Python thread, you could store a pointer to the then current
threadstate.

Hans



More information about the Python-list mailing list