Safety of using pthreads in Gtk+2.0 application

2019-02-18 17:59发布

问题:

I have a simple multithreaded Gtk+2.0 application that acquires data from multiple sources (microphone, webcam, temperature sensor), and displays data from these as images on screen (webcam frame grabs, microphone data represented as oscilloscope renders, text, etc).

It's to my understanding from the Gtk manual and various articles that only the main processing thread should use any Gtk functions/calls that affect the UI. However, the main() entry point blocks on gtk_main() until I close the UI. With the exception of event handlers that are mapped to things like when I click on a button or slider in my UI, it seems the only option left open to me is to spawn a few pthreads and have them do the periodic sampling of data and updating information on-screen in the UI.

I remember from doing some MFC GUI development a long ways back that a similar principle applied: only a single specific thread should be updating the UI elements. How do I accomplish this in C with Gtk+2.0?

Thank you.

回答1:

According to the documentation, the main even loop can accept sources from different threads:

A GMainContext can only be running in a single thread, but sources can be added to it and removed from it from other threads.

So you can inject the code in the UI thread from your working thread by:

  1. creating a GSource (e.g., by using g_idle_source_new);
  2. adding the code you want to be executed with g-source-set-callback;
  3. attaching it to the UI thread context with g_source_attach().

Here is a sample program for GTK+2 and GLib >= 2.32:

#include <gtk/gtk.h>

#define N_THREADS    100
#define N_ITERATIONS 100

GtkWidget *bar;
GMainContext *context;

static gboolean
update_progress_bar(gpointer user_data)
{
    gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(bar),
                                  g_random_double_range(0, 1));
    return G_SOURCE_REMOVE;
}


static gpointer
thread_func(gpointer user_data)
{
    int n_thread = GPOINTER_TO_INT(user_data);
    int n;
    GSource *source;

    g_print("Starting thread %d\n", n_thread);

    for (n = 0; n < N_ITERATIONS; ++n) {
        /* If you want to see anything you should add a delay
         * to let the main loop update the UI, e.g.:
         * g_usleep(g_random_int_range(1234, 567890));
         */
        source = g_idle_source_new();
        g_source_set_callback(source, update_progress_bar, NULL, NULL);
        g_source_attach(source, context);
        g_source_unref(source);
    }

    g_print("Ending thread %d\n", n_thread);
    return NULL;
}


gint
main(gint argc, gchar *argv[])
{
    GtkWidget *window;
    GThread *thread[N_THREADS];
    int n;

    gtk_init(&argc, &argv);

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);

    bar = gtk_progress_bar_new();
    gtk_container_add(GTK_CONTAINER(window), bar);

    context = g_main_context_default();

    for (n = 0; n < N_THREADS; ++n)
        thread[n] = g_thread_new(NULL, thread_func, GINT_TO_POINTER(n));

    gtk_widget_show_all(window);
    gtk_main();

    for (n = 0; n < N_THREADS; ++n)
        g_thread_join(thread[n]);

    return 0;
}


回答2:

I would do your sampling in separate threads, as you suggest. The question then is how you update the UI. What I would do is to use a 'self-pipe'. This is normally done to communicate from signal handlers, but it works just fine between threads when one of the threads can't wait on a condition variable. What you do here is set up a dedicated pipe, write one character to the pipe in the thread that has got the data, and select() on the read end of the pipe in the main program's select() loop. Details here: Using self-pipe, how can I avoid that the event loop stalls on read()? - useful background on its origins here.

You can then make GTK+ listen on the read end of the pipe. Your problem is thus reduced to making GTK+ respond to something on an FD - see here (first answer) for how.