[pygtk] gtk.main in a thread

Dieter Verfaillie dieterv at optionexplicit.be
Thu Dec 15 22:08:10 WST 2011


On Thu, 15 Dec 2011 14:38:37 +0100, Antoon Pardon wrote:
> Does anyone know of possible problems when gtk.main is started in a 
> thread?
>
> I have been experimenting a bit with writing a canvas for programs 
> that just
> need to draw things, without having to bother with mouse-clicks, 
> key-presses
> etc. The idea was to have a thread to would do the minimum necessary, 
> mostly
> expose events and let the rest of the program draw things on the 
> canvas.
>
> Now I have been working on this on two very similar debian boxes. On 
> one it
> works without a problem on the other it keeps getting blocked. It 
> seems to
> boil down to the following bit of code:
>
> def startgtk(func, gtkthread = False):
>   if gtkthread:
>     thrd = Thread(target = gtk.main, name = "GTK thread")
>     thrd.deamon = True
>     thrd.start()
>     func()
>   else:
>     thrd = Thread(target = func, name = "Canvas thread")
>     thrd.deamon = True
>     thrd.start()
>     gtk.main()
>
> Calling this with gtkthread = False, doesn't pose a problem
> but calling it with gtkthread = True makes it block on
> one computer.

gtk.main() just adds a new event source to the default GMainContext 
[1].
Looking at GLib docs [2] we learn that: "... A GMainContext can only
be running in a single thread, ...". Looks to me that what you are
trying to do is not possible?

mvg,
Dieter


[1] snippet from generated gtk.c, it's the g_source_attach
call I'm talking about:

static PyObject *
_wrap_gtk_main(PyObject *self)
{
     GSource *main_watch;
     // Call enable_threads again to ensure that the thread state is 
recorded
     if (pyg_threads_enabled)
	pyg_enable_threads();

     main_watch = pygtk_main_watch_new();
     pyg_begin_allow_threads;
     g_source_attach(main_watch, NULL);
     g_source_unref(main_watch);
     gtk_main();
     g_source_destroy(main_watch);
     pyg_end_allow_threads;
     if (PyErr_Occurred())
         return NULL;
     Py_INCREF(Py_None);
     return Py_None;
}
#line 125761 "gtk/gtk.c"

[2] http://developer.gnome.org/glib/2.28/glib-The-Main-Event-Loop.html



More information about the pygtk mailing list