[問題] GTK使用thread的問題

看板C_and_CPP作者 (Smile)時間14年前 (2010/07/28 21:20), 編輯推噓0(002)
留言2則, 1人參與, 最新討論串1/1
遇到的問題: (題意請描述清楚) 想要使用GTK介面設計一跑馬燈介面程式,當按下按鈕時 建立一Thread修改介面上的圖片營造跑馬燈效果 但是Thread建立之後程式卻當掉無法執行! 希望得到的正確結果: 期望按下按鈕之後建立之Thread會修改介面上之圖片達到跑馬燈效果 程式跑出來的錯誤結果: 程式之結果為GTK程式畫面當掉~但是Thread顯示訊息部分正常 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) Linux , gcc 有問題的code: (請善用置底文標色功能) // 建立之Thread void *thread_function(void *button){ fprintf(stderr,"Enter Thread\n"); GtkWidget *image; GdkPixbuf *pixbuf_a; GdkPixbuf *pixbuf_c; //找尋介面上欲替換之圖片 image=lookup_widget(button,"image8"); //預載跑馬燈亮與滅圖片至pixbuf_a和pixbuf_c之中 pixbuf_a = gdk_pixbuf_new_from_file("a.jpg", NULL); pixbuf_c = gdk_pixbuf_new_from_file("c.jpg", NULL); while(1) { fprintf(stderr,"change red\n"); //設定image為亮的圖片 gtk_image_set_from_pixbuf(image,pixbuf_a); sleep(1); fprintf(stderr,"change black\n"); //設定image為暗的圖片 gtk_image_set_from_pixbuf(image,pixbuf_c); sleep(1); } fprintf(stderr,"End Thread\n"); } //按鈕的Callback Function void on_button3_clicked (GtkButton *button, gpointer user_data) { int res; pthread_t a_thread; //當按鈕按下時建立Thread執行 res = pthread_create(&a_thread,NULL,thread_function, (void *)button); if(res != 0) { perror("Create failed"); } } 補充說明: 我發現程式當掉的原因在於呼叫以下這兩個函式導致 gtk_image_set_from_pixbuf(image,pixbuf_a); gtk_image_set_from_pixbuf(image,pixbuf_c); 當註解掉時發現Thread可以運作正常!! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.116.1.134 ※ 編輯: ppp168p 來自: 140.116.1.134 (07/28 21:21)

07/28 21:56, , 1F
不要在thread裡面做UI的更新動作,你去K一下GTK+手冊裡面
07/28 21:56, 1F

07/28 21:57, , 2F
有關的部份,在這邊就不多說了!
07/28 21:57, 2F
文章代碼(AID): #1CK2wDnl (C_and_CPP)