+void idle_set(event_loop_t *loop, idle_cb_t cb, void *data) {
+ loop->idle_cb = cb;
+ loop->idle_data = data;
+}
+
+bool event_loop_run(event_loop_t *loop, pthread_mutex_t *mutex) {
+ fd_set readable;
+ fd_set writable;
+
+ while(loop->running) {
+ gettimeofday(&loop->now, NULL);
+ struct timeval diff, it, *tv = NULL;
+
+ while(loop->timeouts.head) {
+ timeout_t *timeout = loop->timeouts.head->data;
+ timersub(&timeout->tv, &loop->now, &diff);
+
+ if(diff.tv_sec < 0) {
+ timeout->cb(loop, timeout->data);
+
+ if(timercmp(&timeout->tv, &loop->now, <)) {
+ timeout_del(loop, timeout);
+ }
+ } else {
+ tv = &diff;
+ break;
+ }
+ }
+
+ 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);
+ }
+
+ if(n < 0) {
+ if(sockwouldblock(errno)) {
+ continue;
+ } else {
+ return false;
+ }
+ }
+
+ if(!n) {
+ continue;
+ }