linux - epoll() 是否在 O(1) 中完成工作?

标签 linux network-programming epoll

维基百科说

unlike the older system calls, which operate at O(n), epoll operates in O(1) [2]).

http://en.wikipedia.org/wiki/Epoll

但是,Linux-2.6.38 上 fs/eventpoll.c 的源代码, 似乎它是用一个用于搜索的 RB 树实现的,它有 O(logN)

/*
 * Search the file inside the eventpoll tree. The RB tree operations
 * are protected by the "mtx" mutex, and ep_find() must be called with
 * "mtx" held.
 */
static struct epitem *ep_find(struct eventpoll *ep, struct file *file, int fd)
{

事实上,我看不到任何手册页说 epoll() 的复杂性是 O(1)。 为什么称为 O(1)?

最佳答案

只要您查找 ep_find,这就是有意义的。我只用了几分钟,我看到 ep_find 只被 epoll_ctl 调用。

确实,当您添加描述符 (EPOLL_CTL_ADD) 时,会执行昂贵的操作。但是当做 真正的工作 (epoll_wait) 时,它不是。您只需在开头添加描述符。

总之,问epoll的复杂度是不够的,因为没有epoll系统调用。您想要 epoll_ctlepoll_wait 等的个别复杂性。

其他东西

还有其他原因避免使用 select 并使用 epoll。使用select时,不知道需要注意多少个描述符。所以你必须跟踪最大的并循环到它。

rc = select(...);
/* check rc */
for (s = 0; s <= maxfd; s++) {
    if (FD_ISSET(s)) {
        /* ... */
    }
}

现在使用 epoll 会干净很多:

nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);
/* check nfds */
for (n = 0; n < nfds; ++n) {
    /* events[n].data.fd needs attention */
}

关于linux - epoll() 是否在 O(1) 中完成工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6474602/

相关文章:

linux - 在哪里可以找到 mmap 的源代码?

linux - ARM内核内存布局

c - 在 C 中查找主机地址范围

linux - epoll会通知监听同一个fd的所有进程吗?

linux - 使用 grep 和 awk 过滤 ping 结果完全不起作用

node.js - 某些站点的 Node 请求大部分时间都会导致 ETIMEDOUT 错误

java - 如何在 5 分钟后关闭 HttpUrlConnection 而不会在 Java 中出现异常?

套接字中的 read() 可以返回 EWOULDBLOCK 吗?

c - epoll_wait : maxevents

java - 使用 Maven 构建类路径失败