Using SaveThread and RestoreThread with callbacks
hg
hansgeunsmeyer at earthlink.net
Fri Oct 11 20:55:00 EDT 2002
adam at cardaccess.com.au (Adam Rutkowski) wrote in message news:<b55100a.0210102331.3fb1eb03 at posting.google.com>...
> I've got some Python code calling a C function, which performs a
> PyEval_SaveThread(), does some stuff, then calls a
> PyEvalRestoreThread(). The problem is, part of the stuff it does is
> execute a Python callback function. To do this, it performs a
> PyEvalRestoreThread(), does the callback, then does a
> PyEval_SaveThread(). So the code looks something like this:
>
> x = PyEval_SaveThread()
> C stuff...
> PyEvalRestoreThread(x)
> Callback()
> x = PyEval_SaveThread()
> C stuff...
> PyEvalRestoreThread(x)
Instead of PyEval_SaveThread/RestoreThread I'd say it's safer to use
the macro's Py_BEGIN_ALLOWTHREADS/Py_END_ALLOWTHREADS, because if you
forget or misplace one of them, you'll get a compile-time error.
These calls are only necessary in a multi-threaded application, and
only if the C-stuff may block other threads. If your C-stuff isn't
blocking, I don't see a reason to save/restore the thread state.
> The question is, is this the way I should be doing things? I don't
> quite understand what thread state information is being
> saved/restored, so I don't whether it's possible for code to alter the
> thread state in such a way that restoring to a saved thread state will
> cause problems.
If you use the macro's, it will also be less tempting to do something
with x.
It's surely possible to alter the saved thread state in such a way
that all sorts of funny things start to happen when you restore it.
(The simplest change would be to set x = NULL...) But why would you do
that? :) If the C-stuff isn't touching x (or what it points to), I
don't think the state can alter before it has been restored.
Hans
More information about the Python-list
mailing list