objective-c - NSStream : Is there any airtight defense against blocking?

标签 objective-c cocoa cocoa-touch stream

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.

因此,hasBytesAvailable/hasSpaceAvailable 和流事件似乎都无法提供防止阻塞的保证。有什么方法可以保证流的非阻塞行为?我可以创建一个后台线程来保证非阻塞行为,但我想避免这样做。

此外,我不明白为什么 NSStream 不能提供有保证的非阻塞行为,因为低级 API(select、kqueue 等)可以这样做。有人可以解释为什么会这样吗?

最佳答案

您要么在不同的线程中运行您的阅读或写作,要么您不能使用 NSStream。没有其他方法可以保证非阻塞行为。

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

但由于我们无法检查源代码,因此我们只能对此进行推测。您可能想向 Apple 提交错误,要求他们使用该信息更新文档。

关于objective-c - NSStream : Is there any airtight defense against blocking?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30951833/

相关文章:

iOS 在字符串中查找字符串

iphone - 当 View Controller 被带到 View 堆栈的顶部时,如何让它运行更新代码?

ios - 自动应用 cap insets 的 UIButton 子类

ios - 点击 UITextField 时更改键盘动画持续时间

iphone - UIImage imageNamed 未正确自动释放

ios - NSTimer-控制流程

ios - 越狱检测

cocoa - 在多个地方重用 NSArrayController

ios - 通过 avfoundation 偏移时间码

macos - 如何在 Mac OS X 上使用 cocoa 更改卷名称