当前位置:编程学习 > 网站相关 >>

[Python]Socket高级 -- select I/O复用模型(一)

这个东西以前刚接触,有很多理解不是很清楚。对于模型和不同模型的对比,unix网络编程 有详细的解释

 


因为python是简单调用unix系统的函数,所以找了unix网络编程参看了下,还是比较模糊

select 是属于同步I/O操作,属于I/O复用模型的一种。

这个函数允许进程指示内核等待多个事件中的任一个发生,并仅在一个或多个事件发生或经过某指定的时间后才唤醒进程


模型如下图  recvfrom 是系统调用

 \


文档中这么描述的

select.select(rlist, wlist, xlist[, timeout])
This is a straightforward interface to the Unix select() system call. The first three arguments are sequences of ‘waitable objects’: either integers representing file descriptors or objects with a parameterless method named fileno() returning such an integer:
rlist: wait until ready for reading
wlist: wait until ready for writing
xlist: wait for an “exceptional condition” (see the manual page for what your system considers such a condition


Empty sequences are allowed, but acceptance of three empty sequences is platform-dependent. (It is known to work on Unix but not on Windows.) The optional timeout argument specifies a time-out as a floating point number in seconds. When the timeout argument is omitted the function blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks.
The return value is a triple of lists of objects that are ready: subsets of the first three arguments. When the time-out is reached without a file descriptor becoming ready, three empty lists are returned.
Among the acceptable object types in the sequences are Python file objects (e.g. sys.stdin, or objects returned by open() or os.popen()), socket objects returned by socket.socket(). You may also define a wrapper class yourself, as long as it has an appropriate fileno() method (that really returns a file descriptor, not just a random integer).
Note File objects on Windows are not acceptable, but sockets are. On Windows, the underlying select() function is provided by the WinSock library, and does not handle file descriptors that don’t originate from WinSock.

文档中的大致意思:
这是一个直接调用unix中select()的简单接口。前三个参数都是‘等待对象’的序列:整型的文件描述符或者是一个无参数方法fileno()返回的整数:
* rlist 等待直到准备好写
* wlist 等待直到准备好读
* xlist 等待一种意外的情况 (在手册中查看你的系统中认为的那种情况)
空序列也是允许的,但是能不能3个参数都为空就要由你的系统决定了。(众所都知unix下是行得,windows下不行)timeout指定了一个秒级的浮点型参数表示超时时间当timeout参数为空的时候省略了函数会阻塞直到至少有一个文件描述符已经准备好了。
返回值是三个已经准备好的列表,也是3个参数对象的子集。如果超时了,返回的是三个空列表。其中列表中可以接收的参数类型是Python中的文件参数(例如 sys.stdin 或者是 open() sys.popen()的返回对象),或者是 socket.socket的返回对象。你也可以自己封装成一个类,只要适合fileno()方法
note:在windows中文件对象是无法接受的,但是socket是可以使用的。


这里并没有原理的等的说明

 

 

select
select
select最早于1983年出现在4.2BSD中,它通过一个select()系统调用来监视多个文件描述符的数组,当select()返回后,该数组中就绪的文件描述符便会被内核修改标志位,使得进程可以获得这些文件描述符从而进行后续的读写操作。
select目前几乎在所有的平台上支持,其良好跨平台支持也是它的一个优点,事实上从现在看来,这也是它所剩不多的优点之一。
select的一个缺点在于单个进程能够监视的文件描述符的数量存在最大限制,在Linux上一般为1024,不过可以通过修改宏定义甚至重新编译内核的方式提升这一限制。
另外,select()所维护的存储大量文件描述符的数据结构,随着文件描述符数量的增大,其复制的开销也线性增长。同时,由于网络响应时间的延迟使得大量TCP连接处于非活跃状态,但调用select()会对所有socket进行一次线性扫描,所以这也浪费了一定的开销。


 

补充:Web开发 , Python ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,