[avahi] Integrating Avahi into an application with "select" in the main loop
lennart at poettering.net
Tue Aug 5 07:20:09 PDT 2008
On Tue, 05.08.08 14:27, Nathan Huesken (avahi at lonely-star.org) wrote:
> I am new to avahi and I am a little unsure about how to integrate it
> into an existing application. What I have to do, is call
> "avahi_simple_poll_iterate" on regular intervalls, correct?
Oh no, please don't! The avahi client libraries can be integrated in
several ways into foreign event loops, but doing it based on regularly
called timers is the worst. It burns CPU for nothing, and still delays
Avahi event dispatching unnecessarily. This is really, really bad
style. Using timeouts this way is blatant misuse.
You have several options that are far more elegant:
1) Implement the AvahiPoll structure for your existing event loop,
i.e. implement the seven functions defined here:
Then, pass this struct to avahi_client_new() and the avahi client
will call those functions whenever there is a new FD or timeout to
sleep on. You should then add a new item to your "struct pollfd"
array (in case you uses poll()) or fd_set (in case you use
select()) everytime the watch_new() function you implemented is
called by the avahi client libraries, and similarly for the other
six functions you'd need to implement.
2) A basic event loop implementation that provides AvahiPoll is
AvahiSimplePoll. You could change your program to use this as event
loop implementation instead of a home-grown select()/poll() loop.
3) A event loop adapter that provides AvahiPoll is AvahiGLibPoll that
allows you to use the GLib event loop (which is relatively powerful
and good code) and run the Avahi client on top. Requires you to
adopt the GLib main loop in your program of course. A Qt event loop
adapter is available, too.
4) If you don't want to write the glue code to implement AvahiPoll on
top of your existing event loop, and you don't want to replace your
current event loop code with AvahiSimplePoll or AvahiGLibPoll you
can instead use AvahiThreadedPoll which runs an Avahi-specific
event loop in a seperate thread and leaves your main event loop
untouched. This is sometimes a good idea, i.e. when you cannot
change the main event loop because you don't control the code or
reasons like that. While this might look the easiest way to do it
at first be aware that as soon as you want to exchange data between
the avahi loop and your main event loop you have to think about
locking/synchronization and stuff which requires a good
understanding of how threading works.
There is a small introduction how to use AvahiThreadedPool in the wiki:
Avahi's are very flexible when it comes to integrating them into
foreign event loops. Again, doing it via interval timers is the worst
Lennart Poettering Red Hat, Inc.
lennart [at] poettering [dot] net ICQ# 11060553
http://0pointer.net/lennart/ GnuPG 0x1A015CC4
More information about the avahi