ANN: Stackless Python 0.2
Tim Peters
tim_one at email.msn.com
Tue Jun 29 04:12:07 EDT 1999
[G. David Kuhlman]
> I'll bite. How *does* a thread that calls out to C release the global
> lock?
This is covered in detail in the Python/C API manual (look in your Python
doc distribution), chapter 8. You typically just use a pair of
Python-supplied bracket macros:
... here you own the global lock
Py_BEGIN_ALLOW_THREADS
... now you do not: other Python threads can run, and you can do
... C stuff here as long as you like, in parallel with them
Py_END_ALLOW_THREADS
... now you own the global lock again, and can return to Python
Many examples of these macros can be found in the distribution's C source
code too.
> Would it have to do this thingy that is at the beginning of the
> interpreter loop in python/ceval.c?
>
> if (PyThreadState_Swap(NULL) != tstate)
> Py_FatalError("ceval: tstate mix-up");
> PyThread_release_lock(interpreter_lock);
>
> Would this work? or would it screw up the interpreter?
It won't even compile. interpreter_lock is not an extern symbol: you can't
get at it directly. That's a feature, of course, to discourage chuckleheads
from trying to subvert the published API <wink>.
> Is there a way to do this in a Python script *before* it calls out
> to C.
No: Python-level code must never run unless the thread running it holds the
global lock. Therefore no Python-level code can ever release the global
lock (the instant it did so, it would be illegal code -- so no possibility
for screwing up this way is provided).
This is no real restriction, though. To run external C code at all you have
to put it in a module known to Python (so that Python can resolve the name
*from* Python), and in the typical case where you're calling some
pre-existing thread-safe C function ThreadedSpam, you're not going to stick
ThreadedSpam in a Python module anyway. Instead you'd write your Python C
module with a trivial wrapper function and tell Python about *that*; its
guts will consist of
Py_BEGIN_ALLOW_THREADS
ThreadedSpam();
Py_END_ALLOW_THREADS
it's-only-confusing-if-you-think-about-it-too-much<wink>-ly y'rs - tim
More information about the Python-list
mailing list