[pygtk] embedding pygtk + threads in C

Michael Opitz naxat88 at gmail.com
Mon Apr 16 17:49:42 WST 2007


Hello,

I have a problem with embedded python in C. I want to embed pygtk in
an existing C-GTK application, but unfortunately it isn't possible to
use threads in my embedded python code.
Here is a small example:
C-Code (test.c):
#include <Python.h>
#include <gtk/gtk.h>
#include <pygobject.h>
#include <pygtk/pygtk.h>

int main(int argc, char **argv)
{
    PyObject *pName, *pModule;
    PyObject *func;

    gtk_init(&argc, &argv);
    Py_Initialize();
    init_pygobject();
    init_pygtk();

    pName = PyString_FromString("foo");
    pModule = PyImport_Import(pName);

    if (pModule == NULL) {
        PyErr_Print();
        return 1;
    }

    func = PyObject_GetAttrString(pModule, "init_module");

    if (func && PyCallable_Check(func)) {
        PyObject_CallObject(func, NULL);
    } else {
        PyErr_Print();
        return 1;
    }
    gtk_main();
    Py_DECREF(pModule);
    Py_DECREF(pName);

    Py_Finalize();

      return 0;
}

compiled with:
gcc test.c -o test-pygtk -I/usr/include/python2.4
-I/usr/include/pygtk-2.0/ -L/usr/lib/python2.4/config/ -lpython2.4
-lpthread -lutil `pkg-config --libs --cflags glib-2.0 gthread-2.0
gtk+-2.0 pygtk-2.0` -Xlinker -export-dynamic

And my python-example-code (foo.py):
import threading
import gtk
import gobject

def init_module():
    print "threading_test"
    cntr = Counter()
    cntr.start()

class Counter(threading.Thread):
    def run(self):
        print "in thread"
        i = 0
        while i < 100000:
            print i
            i = i + 1

The output of the example is:
"threading_test"
Neither "in thread" nor the numbers in the loop are printed :/.
I've already read the faq, which suggests to add
gtk.gdk.threads_init() before the  gtk.main()-loop, but unfortunately
the gtk-mainloop is in my C-application. I have tried to add
gtk.gdk.threads_init(), *.threads_enter(), *.threads_leave() in a
PyRun_SimpleString before/after the gtk_main()-loop, but this hasn't
worked either :(.
Any suggestions getting python-threads + pygtk working in embedded C-GTK-apps?

kind regards


More information about the pygtk mailing list