objective-c – NSStream:是否有阻止阻止的密闭防御?

根据
Stream Programming Guide: Polling versus Run-Loop Scheduling部分,最后一段说:

It should be pointed out that neither the polling nor run-loop
scheduling approaches are airtight defenses against blocking. If the
NSInputStream hasBytesAvailable method or the NSOutputStream
hasSpaceAvailable method returns NO, it means in both cases that the
stream definitely has no available bytes or space. However, if either
of these methods returns YES, it can mean that there is available
bytes or space or that the only way to find out is to attempt a read
or a write operation (which could lead to a momentary block). The
NSStreamEventHasBytesAvailable and NSStreamEventHasSpaceAvailable
stream events have identical semantics.

因此,它似乎既没有具有可用性,也没有具有空间可用性,也没有流事件提供阻止阻止的保证.有没有办法通过流获得保证的非阻塞行为?我可以创建一个后台线程来保证非阻塞行为,但我想避免这样做.

此外,我无法理解为什么NSStream无法提供gauranteed非阻塞行为,因为低级API(select,kqueue等)可以这样做.有人可以解释为什么会这样吗?

最佳答案 您可以在另一个线程中运行读取或写入,也可以不使用NSStream.没有其他方法可以保证非阻塞行为.

对于常规文件和套接字,如果在runloop上安排流,则很可能会出现非阻塞行为.但是还有其他类型的流未在文件描述符之上实现.通过将基类记录为并非总是非阻塞,Apple保留了以不能保证非阻塞属性的方式实现不同流的选项.

但由于我们无法检查源代码,我们只能推测这一点.您可能希望向Apple提交一个错误,要求他们使用该信息更新文档.

点赞