GTK中使用多线程

类别:编程语言 点击:0 评论:0 推荐:

刚开始学习GTK编程,中间遇到很多问题,将解决方法记录下来,

希望多多交流

1。添加多线程支持库,先make clean 清除;再将将configure.in文件中的

PKG_CHECK_MODULES(GTK,gtk+-2.0   gdk-2.0,  , exit)改为

PKG_CHECK_MODULES(GTK,gtk+-2.0   gdk-2.0  gthread-2.0 ,  , exit)

2.或者使用手动编译,命令如下

gcc -o thread thread.c `pkg-config --cflags --libs gtk+-2.0 gthread-2.0`

3.示例代码

#include <gtk/gtk.h> static GtkWidget *fixed; static GtkWidget *button1; static GtkWidget *button2; void our_thread1(GtkWidget *button) { gint x,y,towards; x=40; y=40; towards=1; for (;;) { g_usleep(4); gdk_threads_enter(); gtk_fixed_move(GTK_FIXED(fixed),button,x,y); switch(towards) { case 1: x=x+10; if (x==250) towards=2; break; case 2: y=y+10; if (y==250) towards=3; break; case 3: x=x-10; if (x==40) towards=4; break; case 4: y=y-10; if (y==40) towards=5; } gdk_threads_leave(); } } void our_thread2(GtkWidget *button) { gint i,j,forward; i=40; j=40; forward=1; for (;;) { g_usleep(1); gdk_threads_enter(); gtk_fixed_move(GTK_FIXED(fixed),button,i,j); switch(forward) { case 1: i=i+10; if (i==290) forward=2; break; case 2: j=j+10; if (j==250) forward=3; break; case 3: i=i-10; if (i==40) forward=4; break; case 4: j=j-10; if (j==40) forward=5; } gdk_threads_leave(); } } void on_begin(GtkWidget* button,gpointer data) { gtk_widget_set_sensitive(button,FALSE); g_thread_create(our_thread1,button1,FALSE,NULL); g_thread_create(our_thread2,button2,FALSE,NULL); } int main(int argc,char* argv[]) { GtkWidget *window,*view; GtkWidget *vbox,*button,*label; if (!g_thread_supported()) g_thread_init(NULL);

gdk_threads_init(); gtk_init(&argc,&argv); window=gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window),"thread apllication"); g_signal_connect(G_OBJECT(window),"delete_event", G_CALLBACK(gtk_main_quit),NULL); gtk_container_set_border_width(GTK_CONTAINER(window),10); vbox=gtk_vbox_new(FALSE,0); gtk_container_add(GTK_CONTAINER(window),vbox); label=gtk_label_new("Notice! Button is moving"); gtk_box_pack_start(GTK_BOX(vbox),label,FALSE,FALSE,0); view=gtk_viewport_new(NULL,NULL); gtk_box_pack_start(GTK_BOX(vbox),view,FALSE,FALSE,0); fixed=gtk_fixed_new(); gtk_widget_set_usize(fixed,330,330); gtk_container_add(GTK_CONTAINER(view),fixed); button1=gtk_button_new_with_label("1"); button2=gtk_button_new_with_label("2"); gtk_fixed_put(GTK_FIXED(fixed),button1,10,10); gtk_fixed_put(GTK_FIXED(fixed),button2,40,40); button=gtk_button_new_with_label("Start"); gtk_box_pack_start(GTK_BOX(vbox),button,FALSE,FALSE,5); g_signal_connect(G_OBJECT(button),"clicked", G_CALLBACK(on_begin),NULL); gtk_widget_show_all(window); gdk_threads_enter(); gtk_main(); gdk_threads_leave(); return FALSE; } //编译选项如下: //gcc -o thread thread.c `pkg-config --cflags --libs gtk+-2.0 gthread-2.0`

本文地址:http://com.8s8s.com/it/it25277.htm