GTK+3 multithreading

2019-07-27 13:30发布

问题:

I have a program (written in C, currently running on Mac OS X 10.8.4) that simulates a world and updates the world's state multiple times per second.

At startup this program creates a background thread which creates a simple GTK window and calls gtk_main.

After each time the world's state is updated (in the main thread), I would like the window to reflect that change. My first approach was to simply update the GTK widgets after the world was updated, but because that was in a different thread things broke quite messily.

Is there some sort of mechanism where the main thread can update some state on the graphics thread and then queue an event that prompts the graphics thread to redraw? I.e.

void draw() {
    // This can only be called from the graphics thread.
    gtk_label_set(GTK_LABEL(label1), "some state");
}

// This causes draw() to be called on the graphics thread.
gtk_please_redraw_this_thing_on_the_graphics_thread();

Is there any way to do this? Or any tutorials that cover it?

回答1:

Turns out this is quite simple.

First create the function that will do the drawing (on the graphics thread):

gboolean draw_function(GtkWidget *w, GdkEventExpose *event) {
    // Draw things.
    return TRUE;
}

Then, during set up, connect the draw event of your widget to your draw function:

g_signal_connect(G_OBJECT(some_widget), "draw", G_CALLBACK(draw_function),  NULL);

Finally, to force the widget to redraw from another thread you can call:

gtk_widget_queue_draw(some_widget);