问题描述
因此,我一直在尝试找出如何等待(例如)C ++字符串流中的数据,而不是不断检查数据是否存在,这非常消耗CPU.
So, I've been trying to figure out, how to wait for data from a C++ stringstream (for instance), without being constantly checking if data is there, which is quite CPU consuming.
例如,我完全能够从串行设备读取数据,并在没有数据到达时锁定进程,但是不幸的是,我无法弄清楚如何使用C ++流来做到这一点.
I'm perfectly able to read, for instance, from a serial device, and lock the process while no data arrives, but unfortunately I haven't been able to figure how to do that with C++ streams.
我确定我会丢失一些东西,因为cin确实做到了这一点,即等待返回键从istream读取中退出,但是它是如何做到的?
I'm sure I'm missing something, since cin does exactly that, i.e., waits for the return key to step out from istream reading, but how does it do it?
预先感谢您对这个问题的看法.
Thanks in advance for any light on the subject.
推荐答案
流从std::streambuf
获取数据.对于std::cin
,它将调用系统的read()
函数(或等效函数),该函数将阻塞,直到从操作系统移交数据为止.控制台通常发送完整的行.字符串流没有获取新数据的概念,即,当到达当前数据的末尾时,它们将失败.没有阻塞的概念.
Streams obtain data from an std::streambuf
. For the case of std::cin
it calls the system's read()
function (or equivalent) which blocks until data is handed over from the operating system. The console normally sends complete lines. String streams have no concept of getting new data, i.e., they would fail when having reached the end of the current data. There isn't a concept of blocking.
您并没有完全说出自己在做什么,而是从声音的角度尝试在两个线程之间进行数据通信:一次读取并可能阻塞直到数据可用为止,而另一次则填充更多数据.您可以很容易地创建一个相应的流缓冲区:如果没有数据,在条件变量上std::streambuf::underflow()
将wait()
. std::streambuf::overflow()
将适当地设置缓冲区并向条件变量发送信号.显然,有必要进行同步.不过,大多数读写操作都没有进行任何同步.这实际上意味着您将需要两个单独的缓冲区用于输入和输出,并且需要将数据复制到std::streambuf::underflow()
中.
You didn't quite say what you are doing but from the sounds of it try to communicate data between two threads: one reading and possibly blocking until data is available and one filling in more data. You could create a corresponding stream buffer quite easily: std::streambuf::underflow()
would wait()
on a condition variable if there is no data. std::streambuf::overflow()
would set up the buffer appropriately and signal the condition variable. Obviously, there is some need of synchronization necessary. Most of the reading and writing isn't doing any synchronization, though. This effectively means that you will need two separate buffers for input and output and need to copy the data in std::streambuf::underflow()
.
这篇关于如何阻止读取C ++字符串流以等待数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!