Re: gthreads and file operations



On Wed, 14 Apr 2010 10:01:15 +0530
Nischal Rao <rao nischal gmail com> wrote:
Let me explain the entire scenario.

I need to be listening to a socket for data from an external program.
I do this using an infinite loop. Once i get the data, i call a
function and after it returns I go back into infinite loop again.
While all this is happening I also need to listen to some signals
(libwnck signals, which work using the gtk_main() loop). Since
gtk_main() blocks, I created a new thread for the infinite loop.

I got one idea now. I created a separate thread just to listen to a
socket (while the other thread is listening for signals). Is it
possible to listen to the socket through the main event loop? If so,
please let me know how (possibly with an example). I can then safely
remove the thread.

OK, that makes a bit more sense.  As someone else has said,
g_io_add_watch() is intended for this kind of situation.  You can
read/write in the callback using the GIOChannel object but you are not
obliged to do so (you could use unix read/write or sockets recv/sendin
the callback for example).

However, having a dedicated thread for the socket in this kind of case
is not entirely off the wall and may be the better solution if you have
a large amount of traffic, but it does introduce complications.  If you
want to have a dedicated thread for the socket I would still do all
accessing of GTK+ in the main program thread rather than use
gdk_threads_enter() and gdk_threads_leave().  You can send event
callbacks from the server thread to the main program thread using
g_idle_add()/g_idle_add_full() (a somewhat misleading name as with
g_idle_add_full() you can choose any priority you want).  Both those
functions are thread safe (in fact, all of the main loop is thread
safe).

Another solution if you want a multi-threaded solution is to let the gio
module do the work for you (http://library.gnome.org/devel/gio/stable/):
see in particular the gio asynchronous functions. (There is another poor
choice of names here: gio is completely different to, and in some
respects supercedes, GIOChannel, although it is really a replacement
for gnome VFS.)

Chris





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