katrasnikj
katrasnikj

Reputation: 3291

Unable to stop python callbacks from a python C extension

I'm trying to wrap a C++ camera frame acquisition library into Python. I'm having problems with the callback function. I call a python function from a C function with the following code:

PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
result = PyObject_CallObject(my_callback, arglist);
if(result == NULL){
    caller.stopLive();
}
Py_DECREF(result);
Py_DECREF(arglist);
PyGILState_Release(gstate);

The callback works fine. The problem arises when I try to stop the callback with the camera library functions. If the python callback function is short the camera library function is able to stop the callbacks, but if the python callback function takes longer the camera library function is unable to stop the callbacks and the program freezes.

Has anybody had similar problems? Do you have any suggestions about what to try?

Edit: The code for stopping the callbacks is:

static PyObject * stopcallback(PyObject *self, PyObject *args)
{
    if(grabber->isListenerRegistered(pListener)){
        grabber->removeListener(pListener);
        while(grabber->isListenerRegistered(pListener)){
            Sleep(0);
        }
        delete pListener;
        printf("Callback stopped\n");
        Py_RETURN_NONE;
    }
}

I call this function from Python.

Upvotes: 0

Views: 440

Answers (1)

MRAB
MRAB

Reputation: 20654

You say "If the python callback function is short the camera library function is able to stop the callbacks".

I wonder whether the library is unable to remove the callback while it is running (or pending?).

If the callback is short, there are periods of time when it's not being run (or is not pending), so the library is able to remove it, but if the callback is long, it's being run (or is pending) virtually all the time, so the library has no opportunity to remove it.

Upvotes: 2

Related Questions