asynchronous callbacks

hans hans.geuns at scansoft.com
Thu May 23 14:25:49 EDT 2002


I'm writing a Python extension module that has to handle asynchronous
callbacks.  There have been some earlier posts about this, but so far
I haven't found a safe solution.

What I'm doing is this:

I have a global variable

   PyInterpreterState* my_interp;

The initialization function of my extension module looks like:

void initmymodule(void) {
 
   ... 

   PyEval_InitThreads();
   my_interp = PyThreadState_Get()->interp;
}

The callback functions look like:

static void cb_Fun(void* pyFun, T* data)
{
   ...
   // convert data into a Python tuple: arg
   
   ENTER_PY
   res = PyEval_CallObject((PyObject*)pyFun, arg);
   LEAVE_PY
   ...
}

where I'm using two macros:

#define ENTER_PY { PyThreadState* tstate = NULL;\
    if (_PyThreadState_Current == NULL) {\
       tstate = PyThreadState_New(my_interp);\
       PyEval_AquireThread(tstate);\
    }

#define LEAVE_PY if (tstate) {\
    PyThreadState_Clear(tstate);\
    PyThreadState_DeleteCurrent();}\
    } 

The callbacks function can be registered (to a C API) with pyFun
pointing to some Python function (defined in a script). (This Python
function can itself callback into the C API.) In the script, after
registering a function as callback, the main thread is simply looping
in

   while running:
       time.sleep(0)

Variable `running` can at some point be reset by the callback to break
out of the loop.

The problem is that I still get Fatal Python Errors, like
"PyThreadState_Get: no current thread", and sometimes "ceval: tstate
mix-up".
How is this possible? And how can I prevent those errors? What am I
missing?
(I'm working with Python 2.2 on a Win2000 OS.)

Hans



More information about the Python-list mailing list