Python threads question

Makhno mak at imakhno.freeserve.co.uk
Sun Aug 20 14:21:35 EDT 2000


I'm writing a GUI management tool and in order to distinguish it from other
such tools I'm trying to take advantage of multithreading.
I need some confirmations on how Python threads work. From Beazely's book I
am given the impression that the threads are simulated, ie: the Python
interpreter runs in a single low-level thread (where I state 'low-level' to
mean that it was created with a native-OS call) but constantly switches
between instructions in different python threads (every 10 bytecodes of
instructions).

What this effectively means is that when calling an external function (eg: a
C-function extension) that all Python threads must immediately halt until it
returns.
Also, it implies that there is only ever one thread running in the python
interpreter at a time: That that is attached to the python process.

What confuses me is what the macro's
Py_BEGIN_ALLOW_THREADS
and
Py_END_ALLOW_THREADS
do, as apparently they allow the python interpreter to continue running
threads. This seems to imply that when a C-function is called, the python
interpreter creates a new thread which calls the function while the main
thread blocks. Though I'm unconvinced the Python interpreter actually works
like this for performance and portability reasons.

So, suppose I have the following situation: A user presses a button in the
GUI and wishes to create a background thread (to run a calculation in
Python).
That button could initiate a callback that creates a Python thread, runs it
and then returns.
The GUI controls then continue in their own thread, whereas the Python
interpreter starts its calculation and periodically updates the window.
Does anyone see any problems with this method?

Should I wrap every call to the low-level functions (which are thread-safe)
that manipulate the window with Py_BEGIN_ALLOW_THREADS ?






More information about the Python-list mailing list