epoll的多线程安全性问题

来源:互联网 发布:小米怎么备份所有数据 编辑:程序博客网 时间:2024/04/30 15:30

  最近在尝试模仿muduo网络库封装自己的mini网络库,陈硕老师推荐使用one loop per thread + 非阻塞IO的编程模型。于是准备采用一个主事件循环专门读取处理新的连接,而用数个(根据CPU核心数确定)从线程处理各个连接的业务的方式来实现新的服务器,这里就牵涉到一个问题,如果读取连接的主线程向从线程添加新的监听事件的时候会不会存在线程安全性的问题?epoll_ctl是线程安全的,但是若从线程正因epoll_wait阻塞的话,结果如何呢?
  
最权威的参考当然是Linux自带的man手册,原文如下:
  While one thread is blocked in a call to epoll_pwait(), it is possible for another thread to add a file descriptor to the waited-upon epoll instance. If the new file descriptor becomes ready, it will cause the epoll_wait() call to unblock.
For a discussion of what may happen if a file descriptor in an epoll instance being monitored by epoll_wait() is closed in another thread, see select(2)
  大意是,当一个线程阻塞在epoll_wait()上的时候,其他线程向其中添加新的文件描述符是没问题的,如果这个文件描述符就绪的话,阻塞线程的epoll_wait()会被唤醒。但是如果正在监听的某文件描述符被其他线程关闭的话详情见select。查阅select原文如下
  If a file descriptor being monitored by select() is closed in another thread, the result is unspecified. On some UNIX systems, select() unblocks and returns, with an indication that the file descriptor is ready (a subsequent I/O operation will likely fail with an error, unless another the file descriptor reopened between the time select() returned and the I/O operations was performed). On Linux (and some other systems), closing the file descriptor in another thread has no effect on select(). In summary, any application that relies on a particular behavior in this scenario must be considered buggy
  大意是,若一个文件描述符正被监听,其他线程关闭了的话,表现是未定义的。在有些 UNIX系统下,select会解除阻塞返回,而文件描述符会被认为就绪,然而对这个文件描述符进行IO操作会失败(除非这个文件描述符又被分配了),在Linux下,另一个线程关闭文件描述符没有任何影响。但不管怎样,这样做都是2B行为,应当尽量壁面一个线程关闭另一个线程在监听的文件描述符。

0 0
原创粉丝点击