- if(event->time <= now) {
- avl_node_t *node = event_tree->head;
- avl_unlink_node(event_tree, node);
- free(node);
- return event;
+ while(timeout_tree.head) {
+ timeout_t *timeout = timeout_tree.head->data;
+ timersub(&timeout->tv, &now, &diff);
+
+ if(diff.tv_sec < 0) {
+ timeout->cb(timeout->data);
+ if(timercmp(&timeout->tv, &now, <))
+ timeout_del(timeout);
+ } else {
+ tv = &diff;
+ break;
+ }
+ }
+
+ memcpy(&readable, &readfds, sizeof readable);
+ memcpy(&writable, &writefds, sizeof writable);
+
+ int fds = 0;
+
+ if(io_tree.tail) {
+ io_t *last = io_tree.tail->data;
+ fds = last->fd + 1;
+ }
+
+#ifdef HAVE_MINGW
+ LeaveCriticalSection(&mutex);
+#endif
+ int n = select(fds, &readable, &writable, NULL, tv);
+#ifdef HAVE_MINGW
+ EnterCriticalSection(&mutex);
+#endif
+
+ if(n < 0) {
+ if(sockwouldblock(errno))
+ continue;
+ else
+ return false;
+ }
+
+ if(!n)
+ continue;
+
+ for splay_each(io_t, io, &io_tree) {
+ if(FD_ISSET(io->fd, &writable))
+ io->cb(io->data, IO_WRITE);
+ else if(FD_ISSET(io->fd, &readable))
+ io->cb(io->data, IO_READ);