![]() |
![]() |
![]() |
GNet Network Library Reference Manual | ![]() |
---|
Many GNet functions block. That is, they do not return
immediately. For example
gnet_inetaddr_new
performs a DNS lookup
that may take several seconds. This is acceptable for many
programs. But, it is not tolerable in interactive GUI
programs or high-performance servers.
There are two ways to hide blocking. The first is to use
threads. GLib 2.0 includes thread support (GThread). The
second method is to use asynchronous functions. Asynchronous
functions return immediately and call a callback when the
operation is completed. For example,
gnet_inetaddr_new_async
begins an
asynchronous DNS lookup and returns immediately. When the
lookup is complete, a callback is called with the GInetAddr.
Most blocking function in GNet have an asynchronous
counterpart.
To use GNet's asynchronous functions, you must also use the GLib main event loop. Most GTK and Gnome program already do this.
Another common blocking operation is reading or writing to a
GIOChannel (a GLib object).
g_io_channel_read
blocks until there is
data available to read.
g_io_channel_write
blocks until there is
OS buffer space to write to. To determine when a GIOChannel
can be read to or written from without blocking, use GLib's
g_io_add_watch
to set a watch. A
callback is called when the GIOChannel becomes readable or
writable. See the GLib documentation for more information and
GNet's echoclient-async and echoserver-async for an example.