简体   繁体   中英

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?

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, aka 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM