Re: Threads, gtk, pthreads, and gthreads



Gonzalo Aguilar <GAguilarDelgado terra es> writes:

Alternatively, if you really need to update the GUI from a thread, do
g_idle_add (function_that_does_the_updating, ...). In this case,
"function_that_does_the_updating" will be called from the thread that
runs the main loop, so it can safely call gtk functions.
What are you saying?
Can I use a function to do the update from a thread without using
gdk_locks?
So, if the function that updates the GUI is not a thread. Can It be
called safetly?
Even if it's called from a thread? No special requirements?

You can do something like this from a thread:

        typedef struct DataForUpdateGui {
                int foo;
                ...;
        } DataforUpdateGui;

        static gboolean
        update_gui (gpointer data)
        {
                DataForUpdateGui gui_data;

                gui_data = data;

                /* Here you can safely call any gtk function 
                        you want */

                g_free (data);

                return FALSE; /* don't call me again */
        }



        /* in your thread */
        

        ...;
                
        gui_data = g_new (DataForUpdateGui, 1);

        gui_data->foo = bar;

        /* you can do this without any locking */
        g_idle_add (update_gui, gui_data);

        ...;

The g_idle_add() makes sure that update_gui() is called inside the
thread that runs gtk's mainloop. This way, no locking is needed.  GLib
itself will do the locking necessary for g_idle_add().


[I reordered your text a bit]

What about having 10-30 threads working for the main process in a gtk
app?
I know about 255 threads limit (pthreads) but with 10-30 GUI will be
slow, I think.

The 'thread per connection' design does not scale. If you don't ever
expect to use more than 10-30 threads, then it might not matter, but
for many clients, the context switch overhead will make your server
(if that's what it is) slow.

********************************

Threads are for processing incoming datagrams, so I have one for each
host
connected to me.

Then do something along these lines:

        - make sure your sockets are all nonblocking

        - Use GIOChannel to make sure you get callbacks from the main
          loop

        - in your read callbacks, just read all the input into a data
          structure and return. You can tell that there is no more
          input when read() returns -1 with EWOULDBLOCK in errno.

This should make sure you handle all network communication without
using threads and without blocking the user interface.



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