|
这个例子是我从Thomas Stover那里改动过来的。
假使源码文件名称为threadloop.c,则使用
gcc threadloop.c -o threadloop `pkg-config --cflags --libs gtk+-2.0 gthread-2.0`编译。
在winxp mingw下运行测试通过。
- #include <glib.h>
- #include <gtk/gtk.h>
- GMainContext *thread1_context = NULL, *thread2_context = NULL;
- gboolean timeout_callback(gpointer data)
- {
- g_print("timeout_callback()\n");
- return TRUE;
- }
- gboolean idle_callback(gpointer data)
- {
- g_print("idle_callback() in worker thread\n");
- return FALSE;
- }
- gpointer thread2_entry(gpointer data)
- {
- GMainLoop *main_loop;
- GSource *seconds_timeout_source;
- main_loop = g_main_loop_new(thread2_context, FALSE);
- seconds_timeout_source = g_timeout_source_new_seconds(2);
- g_source_set_callback(seconds_timeout_source, timeout_callback, NULL, NULL);
- g_source_attach(seconds_timeout_source, thread2_context);
- g_main_loop_run(main_loop);
- }
- void button_click(GtkWidget *widget, gpointer data)
- {
- GSource *idle_source;
- idle_source = g_idle_source_new();
- g_source_set_callback(idle_source, idle_callback, NULL, NULL);
- g_source_attach(idle_source, thread2_context);
- }
- gboolean delete_event(GtkWidget *widget, GdkEvent *event, gpointer data)
- {
- if( thread2_context)
- g_main_context_unref( thread2_context);
- return FALSE;
- }
- void destroy(GtkWidget *widget, gpointer data)
- {
- gtk_main_quit();
- }
- int main(int argc, char **argv)
- {
- GtkWidget *window;
- GtkWidget *button;
-
- g_thread_init( NULL);
- thread1_context = g_main_context_default();
- thread2_context = g_main_context_new();
-
- gtk_init(&argc, &argv);
- window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
- g_signal_connect( window, "delete-event", G_CALLBACK(delete_event), NULL);
- g_signal_connect( window, "destroy", G_CALLBACK(destroy), NULL);
- gtk_container_set_border_width(GTK_CONTAINER(window), 10);
- button = gtk_button_new_with_label("Idle callback in main thread");
- g_signal_connect( button, "clicked", G_CALLBACK(button_click), NULL);
- gtk_container_add(GTK_CONTAINER(window), button);
- gtk_widget_show_all(window);
- g_thread_create( thread2_entry, NULL, FALSE, NULL);
- gtk_main();
- return 0;
- }
复制代码 |
|