+memcached_server_st *memcached_io_get_readable_server(memcached_st *memc)
+{
+#define MAX_SERVERS_TO_POLL 100
+ struct pollfd fds[MAX_SERVERS_TO_POLL];
+ unsigned int host_index= 0;
+
+ for (unsigned int x= 0;
+ x< memc->number_of_hosts && host_index < MAX_SERVERS_TO_POLL;
+ ++x)
+ {
+ if (memc->hosts[x].read_buffer_length > 0) /* I have data in the buffer */
+ return &memc->hosts[x];
+
+ if (memcached_server_response_count(&memc->hosts[x]) > 0)
+ {
+ fds[host_index].events = POLLIN;
+ fds[host_index].revents = 0;
+ fds[host_index].fd = memc->hosts[x].fd;
+ ++host_index;
+ }
+ }
+
+ if (host_index < 2)
+ {
+ /* We have 0 or 1 server with pending events.. */
+ for (unsigned int x= 0; x< memc->number_of_hosts; ++x)
+ if (memcached_server_response_count(&memc->hosts[x]) > 0)
+ return &memc->hosts[x];
+
+ return NULL;
+ }
+
+ int err= poll(fds, host_index, memc->poll_timeout);
+ switch (err) {
+ case -1:
+ memc->cached_errno = errno;
+ /* FALLTHROUGH */
+ case 0:
+ break;
+ default:
+ for (unsigned int x= 0; x < host_index; ++x)
+ if (fds[x].revents & POLLIN)
+ for (unsigned int y= 0; y < memc->number_of_hosts; ++y)
+ if (memc->hosts[y].fd == fds[x].fd)
+ return &memc->hosts[y];
+ }
+
+ return NULL;
+}
+