std::iostream 是非阻塞的吗?

Is std::iostream non-blocking?

根据 Boost.Iostreams 的提升参考(在第 3.6 节中,最底部):

http://www.boost.org/doc/libs/1_64_0/libs/iostreams/doc/index.html

Although the Boost.Iostreams Filter and Device concepts can accommodate non-blocking i/o, the C++ standard library stream and stream buffer interfaces cannot, since they lack a means to distinguish between temporary and permanent failures to satisfy a read or write request

然而,函数 std::istream::readsome 似乎是非阻塞的,因为可用字符将立即 returned,没有阻塞(RAM 副本除外)等待。我的理解是:

std::istream::read 将阻塞直到 eof 或读取的字符数。

std::istream::readsome 将 return 立即使用从内部缓冲区复制的字符。

在研究非阻塞可移植性时,我在 C++ 标准库中没有发现任何看起来像您认为的那样的东西。

如果您的目标是可移植性,我的解释是最重要的部分是:

http://en.cppreference.com/w/cpp/io/basic_istream/readsome

For example, when used with std::ifstream, some library implementations fill the underlying filebuf with data as soon as the file is opened (and readsome() on such implementations reads data, potentially, but not necessarily, the entire file), while other implementations only read from file when an actual input operation is requested (and readsome() issued after file opening never extracts any characters).

这表示允许使用 iostream 接口的不同实现延迟地完成它们的工作,并且 readsome() 甚至不能保证工作被启动。

不过,我认为你的readsome保证不会阻塞的解释是正确的。

我同意你的看法 readsome 不是阻塞操作。但是,正如指定的那样,作为执行通常称为 "non-blocking I/O".

的接口,它是完全不够的。

首先,无法保证 readsome 永远 return 新数据,即使它可用。所以为了保证你真正取得进步,你最终必须使用阻塞接口之一。

其次,无法知道 readsome 何时会 return 数据。无法 "poll" 流,或获得 "notification" 或 "event" 或 "callback"。可用的非阻塞接口至少需要其中之一。

简而言之,readsome 似乎是为 I/O 流提供非阻塞接口的半生不熟和未指定的尝试。但我从未见过它在生产代码中使用过,我也不希望看到它。

我认为 Boost 文档夸大了论点,因为如您所见,readsome 肯定能够区分临时故障和永久故障。但由于上述原因,他们的结论仍然是正确的。