How to call python from a foreign language thread (C++)

Victor Lin Bornstub at
Tue Feb 3 12:51:36 EST 2009


I am developing a program that use DirectShow to grab audio data from
media files. DirectShow use thread to pass audio data to the callback
function in my program, and I let that callback function call another
function in Python.

I use Boost.Python to wrapper my library, the callback function :

class PythonCallback {
    object m_Function;
    PythonCallback(object obj)
        : m_Function(obj)

    void operator() (double time, const AudioData &data) {
        // Call the callback function in python
        m_Function(time, data);

Here comes the problem, a thread of DirectShow calls my
PythonCallback, namely, call the function in Python. Once it calls, my
program just crash. I found this should be threading problem. Then I
found this document:

It seems that my program can't call to Python's function from thread
directly, because there is Global Interpreter Lock. The python's GIL
is so complex, I have no idea how it works. I'm sorry, what I can do
is to ask. My question is. What should I do before and after I call a
Python function from threads?

It may looks like this.

    void operator() (double time, const AudioData &data) {
        // acquire lock
        m_Function(time, data);
        // release lock

Victor Lin.

More information about the Python-list mailing list