Published: Tuesday, 20 July 2010 13:13
I"ve just been working with GTK+ , a GUI toolkit for C/Linux - but ported to pretty much everything. Initial impressions are quite good, although I am starting to miss Qt/Creator Anyhow, I hit the age-old problem quite quickly. The GUI thread just isn't enough. To start with, I just slapped in a "normal" thread (pthread_t) but when the time came to update the GUI, things started to go pete tong. Here is how I sorted it;
GTK+ is described as "thread aware" rather than "thread safe" so you need to be a bit careful, although after a little investigation it gets very simple.
Firstly, let GLib/GTK know that it may need to share (these should be done FIRST and in this order before any other GLib code gets run);
Then you can start a thread;
- GError *gError = NULL;
- g_thread_create(my_thread, pMyData, FALSE, &Error);
The prototype of the thread function you want to call should look something like this;
- void *my_thread(void *ptr);
Finally all critical code should be wrapped in;
These functions are basically mutex macros which stop two threads accessing the same data at the same time.
Compile in the same way as any other GTK+ program, but ensure the following is added to the compiler options;
Here is a very simple example for clarification;
- // Label that we will change the text of
- GtkWidget *label;
- // The thread.
- void *my_thread(void *pData)
- gtk_label_set_text(GTK_LABEL(label), "Not My Label");
- return 0;
- int main(int argc, char *argv)
- // Thread safe
- // Load GUI.
- gtk_init (&argc, &argv);
- GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
- // Simple label
- label = gtk_label_new("My Label");
- gtk_container_add(GTK_CONTAINER(window), label);
- // Load the thread.
- GError *error = NULL;
- void *pData = 0x00;
- if (!g_thread_create(my_thread, pData, FALSE, &error))
- g_printerr ("Failed to create thread: %sn", error->message);
- return 1;
- // Run window.
- return 0;
It can be compiled using the following;
- gcc -Wall -g shoal_test.c `pkg-config --cflags gtk+-2.0` `pkg-config --libs gtk+-2.0` -lgthread-2.0
Its as simple as that. I hope it helps someone!