- 与
select.select
一起使用时,套接字是否应设置为非阻塞?在 Python 中? - 它们是否存在有什么区别?
偶尔我发现调用send
在返回可发送的套接字上将阻塞。此外,我发现 blocking套接字通常会发送给定的整个缓冲区 (128 KiB)。在非阻塞模式下,发送将接受更少的字节(与前面给出的示例相比为 20-40 KiB)并且返回更快。我正在使用 Python 3.1 on Lucid .
最佳答案
不幸的是,答案可能取决于操作系统。我只回答关于 Linux 的问题。
我不知道 select 中关于阻塞/非阻塞套接字的区别,但在 linux 上,select
系统调用手册页的“BUGS”部分有这个:
Under Linux, select() may report a socket file descriptor as "ready for reading", while nevertheless a subsequent read blocks. This could for example happen when data has arrived but upon examination has wrong checksum and is discarded. There may be other circumstances in which a file descriptor is spuriously reported as ready. Thus it may be safer to use O_NONBLOCK on sockets that should not block.
我怀疑上面的 python 抽象是否可以“隐藏”这个问题而没有副作用。
至于发送更多数据的阻塞写入,这是意料之中的。如果套接字阻塞,send
将阻塞,直到有足够的缓冲区空间来传递您的整个请求。如果套接字是非阻塞的,它只会发送当前适合套接字发送缓冲区的数据。
关于python - 套接字应该是非阻塞的以便在 Python 中使用 select 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5237733/