user2460733
user2460733

Reputation:

C - GTK3 and Threads

I wrote a program in C to test dynamic GTK label changing, but the program rendomly stops updating the GUI after some iterations.

Using the PThreads API to create a new thread - directly before invoking gtk_main() - I thought that this would be the right approach, since the GTK Refernce Manual says that the gdk_threads_* functions are deprecated and does not suggest any alternatives.

This is the procedure & entry point for the newly created thread. It simply concats a constant string with the increasing number of the iteration and sets it to the label, but somehow after an unpredictable amount of iterations stops updating.

void * change_text(void * args)
{
    char * initialText = (char *) malloc(strlen(gtk_label_get_text((GtkLabel *) args)) * sizeof(char));
    strcpy(initialText, gtk_label_get_text((GtkLabel *) args));

    char setnew[512];

    int x = 1;
    while(1) {
        printf("%s\n", initialText);
        sprintf(setnew, "%s %d", initialText, x++);

        gtk_label_set_text(GTK_LABEL(args), setnew);

        sleep(1);
        bzero(setnew, 512);
    }
}

The thread doesn't crash.

Can somebody help me what would be the correct approach for dynamically updating labels, buttons, ... in GTK3?

Upvotes: 0

Views: 3268

Answers (2)

Fabio Di Matteo
Fabio Di Matteo

Reputation: 45

You can use g_idle_add ((GSourceFunc) yourfunc, NULL ); inside the thread to run yourfunc. In this link all the code:

http://www.freemedialab.org/wiki/doku.php?id=programmazione:gtk:gtk_e_i_thread

Upvotes: 1

meskobalazs
meskobalazs

Reputation: 16041

The problem is that you want to update the GUI in another thread. This is not really a good idea. What you should do, when you are building a GUI application (this is not GTK+ specific):

  • Update the GUI in the main thread, a.k.a. the GUI thread
  • Do the heavy lifting in a background thread, then notify the GUI

For the notification part, you should use the IPC mechanisms of pthreads.

Upvotes: 3

Related Questions