# [Asterisk-Dev] Re: ast_waitfor*() question

Luigi Rizzo rizzo at icir.org
Tue Jun 21 10:58:32 MST 2005

```two related questions
1) ast_waitfor_n_fd() maps EINTR into *ms = 0

/* Simulate a timeout if we were interrupted */
if (errno != EINTR)
*ms = -1;
else
*ms = 0;

whereas ast_waitfor_nandfds() has the *ms = 0 part commmented out:

if (errno != EINTR)
*ms = -1;
else {
/* Just an interrupt */
#if 0
*ms = 0;
#endif

shouldn't they do the same thing ?

2) ast_waitfor_nandfds() sets *outfd = -99999 by default. I cannot find
anything special about this value, the rest of the code uses -1
to mark an invalid descriptor. Again, could we use -1 there as well
so the two functions could be merged into one ?

thanks
luigi

On Tue, Jun 21, 2005 at 10:33:52AM -0700, Luigi Rizzo wrote:
> functions ast_waitfor_n_fd() and ast_waitfor_nandfds() have a performance
> issue that I would like to fix.
>
> ast_waitfor_n_fd() has an O(N^2) loop to figure out the 'winner' fd
> because ast_fdisset() itself is O(N):
>
>     for (x=0;x<n;x++) {
>         if (fds[x] > -1) {
>             if ((res = ast_fdisset(pfds, fds[x], y, &spoint))) {
>                 ...
>             }
>         }
>     }
>
> ast_waitfor_nandfds() is even worse - the loop is O(N^2 * AST_MAX_FDS)
>
>     for (x=0;x<n;x++) {
>         for (y=0;y<AST_MAX_FDS;y++) {
>             if (c[x]->fds[y] > -1) {
>                 if ((res = ast_fdisset(pfds, c[x]->fds[y], max, &spoint))) {
>                     ....
>                 }
>             }
>         }
>     }
>
>
> Both can be reduced to O(N), trivially for ast_waitfor_n_fd() :
>
>     for (x = 0; x < y; x++) {
>         if ((res = pfds[x].revents) != 0) {
>             winner = pfds[x].fd;
>             if (exception)
>                 *exception = (res & POLLPRI) ? -1 : 0;
>         }
>     }
>
>
> and only slightly harder for ast_waitfor_nandfds() by keeping track,
> while building the pfds[] array, which channel is associated to each entry.
>
> I have only one question though - if multiple channels are ready,
> ast_waitfor_nandfds() seems to privilege the highest numbered one.
> Do I have to preserve this behaviour or it does not matter who
> the winner is ? I do not see it specified elsewhere.
>
>         cheers
>         luigi

```