Re: Gtk+ and multithreating



I'm doing a multithreading program using GTK+ (a POS emulator) and I'm using
something like that:


/****************************************************************************************************/
#include <gtk/gtk.h>

gpointer cb_t1(gpointer d)
{
   while (1)
   {
       g_usleep(1000 * 2000);
       gdk_threads_enter(); /* my turn! i'll use GTK+... */
       g_debug("thread 1 in action!");
       gtk_label_set_text(GTK_LABEL(d), "thread1");
       gdk_flush(); /* flushes all pending commands... */
       gdk_threads_leave(); /* i'm done! */
   }
}

gpointer cb_t2(gpointer d)
{
   while (1)
   {
       g_usleep(1000 * 3000);
       gdk_threads_enter(); /* my turn! i'll use GTK+... */
       g_debug("thread 2 in action!");
       gtk_label_set_text(GTK_LABEL(d), "thread2");
       gdk_flush(); /* flushes all pending commands... */
       gdk_threads_leave(); /* i'm done! */
   }
}

gboolean cb_key_press
(GtkWidget *w, GdkEventKey *e, gpointer d)
{
   g_message("%d", e->keyval);
}

int main(int argc, char *argv[])
{
   GtkWidget *window;
   GtkWidget *label;

   g_thread_init(NULL); /* glib threads init */
   gdk_threads_init(); /* gdk threads init */
   gdk_threads_enter(); /* protects the main loop */

   gtk_init(&argc, &argv);

   window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
   gtk_widget_set_events(window, GDK_KEY_PRESS_MASK);
   g_signal_connect(
       G_OBJECT(window),
       "destroy",
       G_CALLBACK(gtk_main_quit),
       NULL);
   g_signal_connect(
       G_OBJECT(window),
       "key-press-event",
       G_CALLBACK(cb_key_press),
       NULL);
   gtk_widget_show(window);

   label = gtk_label_new("");
   gtk_container_add(GTK_CONTAINER(window), label);
   gtk_widget_show(label);

   g_thread_create(cb_t1, (gpointer) label, FALSE, NULL);
   g_thread_create(cb_t2, (gpointer) label, FALSE, NULL);

   gtk_main();

   gdk_threads_leave(); /* we're done... */
}
/****************************************************************************************************/

Here we have three threads unsing the GTK+ without conflicts...

Basically, we must protect the gtk_main() loop with the
gdk_threads_enter()/gdk_threads_leave()  pair and for each function that
uses the GTK+ we must surrounding that with a
gtk_thread_enter()/gdk_threads_leave() pair.

This functions just lock a previously definied mutex (or something like
that).

More info:
http://developer.gnome.org/doc/API/2.0/gdk/gdk-Threads.html
http://developer.gnome.org/doc/API/2.0/glib/glib-Threads.html

PS: Sorry Michael. =P



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]