c++ callbacks and thread safety

Michal Wallace sabren at manifestation.com
Sun Feb 13 09:47:21 CET 2000


Hey All!

Since I don't really know my way around C/C++, I was pretty nervous about
trying to reimplement a python extension as a .pyd.... But after reading the
docs, I tried it out and managed to get my MIDI input module *almost*
working.
(Pretty amazing testimony to how easy extending python is!)

But, there is one small problem.. MIDI input (at least on win32) requires a
callback, which I've set up to look basically like this:

//////////
void CALLBACK _midiCallback( .... )
{
    PyEval_CallObject (a_callable_PyObject, NULL);
}
/////////

My python script looks like this:

###
import winmidi
import sys

def myCallback():
    print "in myCallback!"

allDone = 0

winmidi.inOpen(myCallback)
while allDone == 0:
    if sys.stdin.readline()[:-1] == "quit":
        allDone = 1

winmidi.inClose()
###

It seems to work just fine... until I press a note on my keyboard. Then
python crashes.

BUT.. if I change the loop to:

###
while allDone == 0:
    pass
###

... then it works perfectly, meaning the "in my callback" message prints out
every time I hit a note.

I gather that I need to do some kind of thread checking here... but I don't
understand what to do. I tried putting Py_BEGIN_ALLOW_THREADS
and Py_END_ALLOW_THREADS in various places, but that didn't seem
to help... Besides, I'm just guessing now, and I want to understand... Can
someone tell me what I'm doing wrong, or perhaps point me in the right
direction? Thanks! :)

[I tried looking at some of the source for the win32 extensions that use
callbacks,
but I don't know enough C++ to know what to look for...]

-Michal
http://www.sabren.com/






More information about the Python-list mailing list