Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1684847
  • 博文数量: 347
  • 博客积分: 9328
  • 博客等级: 中将
  • 技术积分: 2680
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-29 23:45
文章分类

全部博文(347)

文章存档

2016年(1)

2013年(4)

2012年(207)

2011年(85)

2010年(50)

分类: C/C++

2012-11-17 21:26:29

最近有朋友在面试的时候被问了select 和epoll效率差的原因,和一般人一样,大部分都会回答select是轮询、epoll是触发式的,所以效率高。这个答案听上去很完美,大致也说出了二者的主要区别。
今天闲来无事,翻看了下内核代码,结合内核代码和大家分享下我的观点。

一、连接数
我本人也曾经在项目中用过select和epoll,对于select,感触最深的是linux下select最大数目限制(windows 下似乎没有限制),每个进程的select最多能处理FD_SETSIZE个FD(文件句柄),
如果要处理超过1024个句柄,只能采用多进程了。
常见的使用slect的多进程模型是这样的: 一个进程专门accept,成功后将fd通过unix socket传递给子进程处理,父进程可以根据子进程负载分派。曾经用过1个父进程+4个子进程 承载了超过4000个的负载。
这种模型在我们当时的业务运行的非常好。epoll在连接数方面没有限制,当然可能需要用户调用API重现设置进程的资源限制。

二、IO差别
1、select的实现

这段可以结合linux内核代码描述了,我使用的是2.6.28,其他2.6的代码应该差不多吧。
先看看select:
select系统调用的代码在fs/Select.c下,

  1. asmlinkage long sys_select(int n, fd_set __user *inp, fd_set __user *outp,
  2.             fd_set __user *exp, struct timeval __user *tvp)
  3. {
  4.     struct timespec end_time, *to = NULL;
  5.     struct timeval tv;
  6.     int ret;

  7.     if (tvp) {
  8.         if (copy_from_user(&tv, tvp, sizeof(tv)))
  9.             return -EFAULT;

  10.         to = &end_time;
  11.         if (poll_select_set_timeout(to,
  12.                 tv.tv_sec + (tv.tv_usec / USEC_PER_SEC),
  13.                 (tv.tv_usec % USEC_PER_SEC) * NSEC_PER_USEC))
  14.             return -EINVAL;
  15.     }

  16.     ret = core_sys_select(n, inp, outp, exp, to);
  17.     ret = poll_select_copy_remaining(&end_time, tvp, 1, ret);

  18.     return ret;
  19. }

前面是从用户控件拷贝各个fd_set到内核空间,接下来的具体工作在core_sys_select中,

  1. core_sys_select->do_select,真正的核心内容在do_select里:
  2. int do_select(int n, fd_set_bits *fds, struct timespec *end_time)
  3. {
  4.     ktime_t expire, *to = NULL;
  5.     struct poll_wqueues table;
  6.     poll_table *wait;
  7.     int retval, i, timed_out = 0;
  8.     unsigned long slack = 0;

  9.     rcu_read_lock();
  10.     retval = max_select_fd(n, fds);
  11.     rcu_read_unlock();

  12.     if (retval < 0)
  13.         return retval;
  14.     n = retval;

  15.     poll_initwait(&table);
  16.     wait = &table.pt;
  17.     if (end_time && !end_time->tv_sec && !end_time->tv_nsec) {
  18.         wait = NULL;
  19.         timed_out = 1;
  20.     }

  21.     if (end_time && !timed_out)
  22.         slack = estimate_accuracy(end_time);

  23.     retval = 0;
  24.     for (;;) {
  25.         unsigned long *rinp, *routp, *rexp, *inp, *outp, *exp;

  26.         set_current_state(TASK_INTERRUPTIBLE);

  27.         inp = fds->in; outp = fds->out; exp = fds->ex;
  28.         rinp = fds->res_in; routp = fds->res_out; rexp = fds->res_ex;

  29.         for (i = 0; i < n; ++rinp, ++routp, ++rexp) {
  30.             unsigned long in, out, ex, all_bits, bit = 1, mask, j;
  31.             unsigned long res_in = 0, res_out = 0, res_ex = 0;
  32.             const struct file_operations *f_op = NULL;
  33.             struct file *file = NULL;

  34.             in = *inp++; out = *outp++; ex = *exp++;
  35.             all_bits = in | out | ex;
  36.             if (all_bits == 0) {
  37.                 i += __NFDBITS;
  38.                 continue;
  39.             }

  40.             for (j = 0; j < __NFDBITS; ++j, ++i, bit <<= 1) {
  41.                 int fput_needed;
  42.                 if (i >= n)
  43.                     break;
  44.                 if (!(bit & all_bits))
  45.                     continue;
  46.                 file = fget_light(i, &fput_needed);
  47.                 if (file) {
  48.                     f_op = file->f_op;
  49.                     mask = DEFAULT_POLLMASK;
  50.                     if (f_op && f_op->poll)
  51.                         mask = (*f_op->poll)(file, retval ? NULL : wait);
  52.                     fput_light(file, fput_needed);
  53.                     if ((mask & POLLIN_SET) && (in & bit)) {
  54.                         res_in |= bit;
  55.                         retval++;
  56.                     }
  57.                     if ((mask & POLLOUT_SET) && (out & bit)) {
  58.                         res_out |= bit;
  59.                         retval++;
  60.                     }
  61.                     if ((mask & POLLEX_SET) && (ex & bit)) {
  62.                         res_ex |= bit;
  63.                         retval++;
  64.                     }
  65.                 }
  66.             }
  67.             if (res_in)
  68.                 *rinp = res_in;
  69.             if (res_out)
  70.                 *routp = res_out;
  71.             if (res_ex)
  72.                 *rexp = res_ex;
  73.             cond_resched();
  74.         }
  75.         wait = NULL;
  76.         if (retval || timed_out || signal_pending(current))
  77.             break;
  78.         if (table.error) {
  79.             retval = table.error;
  80.             break;
  81.         }

  82.         /*
  83.          * If this is the first loop and we have a timeout
  84.          * given, then we convert to ktime_t and set the to
  85.          * pointer to the expiry value.
  86.          */
  87.         if (end_time && !to) {
  88.             expire = timespec_to_ktime(*end_time);
  89.             to = &expire;
  90.         }

  91.         if (!schedule_hrtimeout_range(to, slack, HRTIMER_MODE_ABS))
  92.             timed_out = 1;
  93.     }
  94.     __set_current_state(TASK_RUNNING);

  95.     poll_freewait(&table);

  96.     return retval;
  97. }

上面的代码很多,其实真正关键的代码是这一句:

  1. mask = (*f_op->poll)(file, retval ? NULL : wait);

这个是调用文件系统的 poll函数,不同的文件系统poll函数自然不同,由于我们这里关注的是tcp连接,而socketfs的注册在 net/Socket.c里。
register_filesystem(&sock_fs_type); 
socket文件系统的函数也是在net/Socket.c里:

  1. static const struct file_operations socket_file_ops = {
  2.     .owner = THIS_MODULE,
  3.     .llseek = no_llseek,
  4.     .aio_read = sock_aio_read,
  5.     .aio_write = sock_aio_write,
  6.     .poll = sock_poll,
  7.     .unlocked_ioctl = sock_ioctl,
  8. #ifdef CONFIG_COMPAT
  9.     .compat_ioctl = compat_sock_ioctl,
  10. #endif
  11.     .mmap = sock_mmap,
  12.     .open = sock_no_open, /* special open code to disallow open via /proc */
  13.     .release = sock_close,
  14.     .fasync = sock_fasync,
  15.     .sendpage = sock_sendpage,
  16.     .splice_write = generic_splice_sendpage,
  17.     .splice_read = sock_splice_read,
  18. };

从sock_poll跟随下去,
最后可以到 net/ipv4/tcp.c的
unsigned int tcp_poll(struct file *file, struct socket *sock, poll_table *wait) 
这个是最终的查询函数,
也就是说select 的核心功能是调用tcp文件系统的poll函数,不停的查询,如果没有想要的数据,主动执行一次调度(防止一直占用cpu),直到有一个连接有想要的消息为止。
从这里可以看出select的执行方式基本就是不同的调用poll,直到有需要的消息为止,如果select 处理的socket很多,这其实对整个机器的性能也是一个消耗。

2、epoll的实现

epoll的实现代码在 fs/EventPoll.c下,
由于epoll涉及到几个系统调用,这里不逐个分析了,仅仅分析几个关键点,
第一个关键点在
static int ep_insert(struct eventpoll *ep, struct epoll_event *event,
             struct file *tfile, int fd) 
这是在我们调用sys_epoll_ctl 添加一个被管理socket的时候调用的函数,关键的几行如下:
epq.epi = epi;
    init_poll_funcptr(&epq.pt, ep_ptable_queue_proc);

    /*
     * Attach the item to the poll hooks and get current event bits.
     * We can safely use the file* here because its usage count has
     * been increased by the caller of this function. Note that after
     * this operation completes, the poll callback can start hitting
     * the new item.
     */
    revents = tfile->f_op->poll(tfile, &epq.pt); 
这里也是调用文件系统的poll函数,不过这次初始化了一个结构,这个结构会带有一个poll函数的callback函数:ep_ptable_queue_proc,
在调用poll函数的时候,会执行这个callback,这个callback的功能就是将当前进程添加到 socket的等待进程上。

  1. static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead,
  2.                  poll_table *pt)
  3. {
  4.     struct epitem *epi = ep_item_from_epqueue(pt);
  5.     struct eppoll_entry *pwq;

  6.     if (epi->nwait >= 0 && (pwq = kmem_cache_alloc(pwq_cache, GFP_KERNEL))) {
  7.         init_waitqueue_func_entry(&pwq->wait, ep_poll_callback);
  8.         pwq->whead = whead;
  9.         pwq->base = epi;
  10.         add_wait_queue(whead, &pwq->wait);
  11.         list_add_tail(&pwq->llink, &epi->pwqlist);
  12.         epi->nwait++;
  13.     } else {
  14.         /* We have to signal that an error occurred */
  15.         epi->nwait = -1;
  16.     }
  17. }

注意到参数 whead 实际上是 sk->sleep,其实就是将当前进程添加到sk的等待队列里,当该socket收到数据或者其他事件触发时,会调用
sock_def_readable 或者sock_def_write_space 通知函数来唤醒等待进程,这2个函数都是在socket创建的时候填充在sk结构里的。
从前面的分析来看,epoll确实是比select聪明的多、轻松的多,不用再苦哈哈的去轮询了。
阅读(1062) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~