About multi threads



I use gtk with multi-threads but met some problems:

if I use the "g_thread_init(NULL)" in the main() function, then the
other thread function can not access the widget which is created in the
main() function. But if I do not use g_thread_init(NULL), then
everything is fine, all threads can access the widgets.

I wonder why?

Also, if I do not use g_thread_init(NULL), then there will be the
problem of simultaneously accessing.

The following is a simple sample code.

1. There is a thread function called:  "the_ui_thread()"
     In that function, there is a loop which continuely recieve the
message(simply a integer) from the server and then display it in an
entry (which is a global widget and is created by create_window() in
main())

2.    In the main(), I will add more callback function (such as button
clicked).

What I want to do is:

1.  Both threads can access the widgets
2.  Each time, when a thread is running, only after it runs all the
functions in it(fully completed),then it can change to the other thread.

I test many ways to do that, but all failed.

Any one can help me?? Please teach me ASAP

Thanks!!!!!

#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include "interface.h"

#define MSGKEY 3756

GtkWidget* window1;
bool pause1;


void *the_ui_thread(void *ptr)
{
     struct msgbuf
     {
          int mtype;
          int mtext;
     }buf;

     int msqid;
     char tempstring[50];

     msqid=msgget(MSGKEY,0666|IPC_CREAT);

     gdk_threads_enter();

     while(1)
     {
               msgrcv(msqid,&buf,sizeof(struct msgbuf),1,0);
                sprintf(tempstring,"%d",buf.mtext);
               gtk_entry_set_text(GTK_ENTRY(entry1),tempstring);
               gtk_widget_show(window1);
      }

    gdk_threads_leave();
}

int main (int argc, char *argv[])
{
     pthread_t tid;

 //g_thread_init(NULL);

     gtk_init(&argc,&argv);

      window1=create_window1 ();
     gtk_widget_show (window1);


    gdk_threads_enter();

    pthread_create(tid,NULL,the_ui_thread,NULL);

     gtk_main ();

     gdk_threads_leave();

}



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]