+
+ if(loop->idle_cb) {
+ it = loop->idle_cb(loop, loop->idle_data);
+
+ if(it.tv_sec >= 0 && (!tv || timercmp(&it, tv, <))) {
+ tv = ⁢
+ }
+ }
+
+ memcpy(&readable, &loop->readfds, sizeof(readable));
+ memcpy(&writable, &loop->writefds, sizeof(writable));
+
+ int fds = 0;
+
+ if(loop->ios.tail) {
+ io_t *last = loop->ios.tail->data;
+ fds = last->fd + 1;
+ }
+
+ // release mesh mutex during select
+ if(mutex) {
+ pthread_mutex_unlock(mutex);
+ }
+
+ int n = select(fds, &readable, &writable, NULL, tv);
+
+ if(mutex) {
+ pthread_mutex_lock(mutex);
+ }
+
+ gettimeofday(&loop->now, NULL);
+
+ if(n < 0) {
+ if(sockwouldblock(errno)) {
+ continue;
+ } else {
+ return false;
+ }
+ }
+
+ if(!n) {
+ continue;
+ }
+
+ // Normally, splay_each allows the current node to be deleted. However,
+ // it can be that one io callback triggers the deletion of another io,
+ // so we have to detect this and break the loop.
+
+ loop->deletion = false;
+
+ for splay_each(io_t, io, &loop->ios) {
+ if(FD_ISSET(io->fd, &writable) && io->cb) {
+ io->cb(loop, io->data, IO_WRITE);
+ }
+
+ if(loop->deletion) {
+ break;
+ }
+
+ if(FD_ISSET(io->fd, &readable) && io->cb) {
+ io->cb(loop, io->data, IO_READ);
+ }
+
+ if(loop->deletion) {
+ break;
+ }
+ }
+ }
+
+ return true;
+}
+
+void event_flush_output(event_loop_t *loop) {
+ for splay_each(io_t, io, &loop->ios)
+ if(FD_ISSET(io->fd, &loop->writefds)) {
+ io->cb(loop, io->data, IO_WRITE);
+ }
+}
+
+void event_loop_start(event_loop_t *loop) {
+ loop->running = true;
+}
+
+void event_loop_stop(event_loop_t *loop) {
+ loop->running = false;
+}
+
+void event_loop_init(event_loop_t *loop) {
+ loop->ios.compare = (splay_compare_t)io_compare;
+ loop->timeouts.compare = (splay_compare_t)timeout_compare;
+ loop->signals.compare = (splay_compare_t)signal_compare;
+ loop->pipefd[0] = -1;
+ loop->pipefd[1] = -1;
+ gettimeofday(&loop->now, NULL);
+}
+
+void event_loop_exit(event_loop_t *loop) {
+ for splay_each(io_t, io, &loop->ios) {
+ splay_unlink_node(&loop->ios, node);