Qt QIODevice::Unbuffered 理解

Unbuffered 就是无缓冲方式。何谓缓冲?科学释意就是我们常说的 buffer, 具体指针对 I/O 的缓存。它可以有很多更加具体的形式:

+-------------------+-------------------+
| Process A         | Process B         |
+-------------------+-------------------+
| C runtime library | C runtime library | C RTL buffers
+-------------------+-------------------+
|               OS caches               | Operating system buffers
+---------------------------------------+
|      Disk controller hardware cache   | Disk hardware buffers
+---------------------------------------+
|                   Disk                |
+---------------------------------------+

 

如图所示,有 C/C++ 语言层面的、操作系统层面的,甚至硬盘层面的。其作用在于,创造一个中间层,从而避免频繁调用底层"昂贵"资源的调配权。

如你这里提到的写文件,你可能希望一个字节一个字节的往硬盘上写。但"写硬盘"存在 I/O 瓶颈,比起内存要慢许多。如果没有 buffer, 你每写一个字节的数据,就要去写一次硬盘,想象一下,会多么的慢。

而有了缓冲呢?你写入的字节通通都先放到一块 buffer 上(内存),由于是内存操作,所以速度非常快。等你写完、或者缓存的量到达某个限度,语言的 RTL 或 OS 才会将这一块数据,一次性写入硬盘中。

比较一下上述区别,体会一下缓冲的含义。这种策略,不仅常见于 I/O,上自浏览器的 cache, 下自 CPU 的高速缓存,其实都会用到。

形象比喻(可能不雅)

譬如拉屎,你是拉一点就冲厕所呢?还是都拉完,才冲?

好吧,这是告诉你具体问题具体分析,你需不需要设置 Unbuffered,要看你使用的时机。


最后一点注意:

Certain flags, such as Unbuffered and Truncate, are meaningless when used with some subclasses. Some of these restrictions are implied by the type of device that is represented by a subclass. In other cases, the restriction may be due to the implementation, or may be imposed by the underlying platform; for example, QTcpSocket does not support Unbuffered mode, and limitations in the native API prevent QFile from supporting Unbuffered on Windows.

即,QTcpSocket 不支持 Unbuffered,Windows 原生 API 也对该功能有限制。言下之意:尽量避免使用。

回复

猜你喜欢

转载自blog.csdn.net/qq_41607336/article/details/117791728