GTK+3 multithreading

大城市里の小女人 提交于 2019-12-11 13:10:47

问题


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);


来源:https://stackoverflow.com/questions/17439933/gtk3-multithreading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!