How to block C ++ string reading to wait for data

So, I tried to figure out how to wait for data from a C ++ string stream (for example), without constantly checking to see if there is data there, which the processor consumes.

I can read, for example, from a serial device and block the process until the data arrives, but, unfortunately, I could not figure out how to do this with C ++ streams.

I'm sure something is missing from me, since cin does just that, i.e. waits for the return key to exit istream reading, but how does it do it?

Thanks in advance for any light on this subject.

+4
source share
2 answers

Streams get data from std::streambuf . For the case of std::cin it calls the read() function of the system (or equivalent), which blocks until data is transferred from the operating system. The console usually sends complete lines. String streams do not have the concept of getting new data, i.e. They will fail when they reach the end of the current data. There is no lock concept.

You didn’t quite say what you are doing, but because of the sounds they are trying to transfer data between two streams: one reading and, possibly, blocking until the data is available, and one filling in more data. You can create the appropriate stream buffer quite easily: std::streambuf::underflow() will wait() in the condition variable if there is no data. std::streambuf::overflow() will appropriately configure the buffer and signal the condition variable. Obviously, some synchronization is needed. However, most of the reading and writing does not perform any synchronization. This actually means that you will need two separate buffers for input and output and you need to copy the data to std::streambuf::underflow() .

+2
source

You can not. The only way std::stringstream knows that there isn’t any extra data is that there is no data in the stream.

This is an interesting thought, however. << on std::stringstream returns only true if the recording side was closed. The only problem with the idea is that std::stringstream has no idea about opening or closing.

The real question, however, is what are you trying to achieve. std::stringstream works in the process, and in this case there is really no need for formatting (this is an abstraction of iostreams in general). Just enter the source objects in std::deque . The only thing you will need to worry about formatting when you are communicating with the look. std::istringstream very useful, for example, when you get a string from std::getline in a file or from another source. Similarly, std::ostringstream is useful when formatting data for some external source, which requires a string of some sort. But I never found use for std::stringstream ; it is there apparently for reasons of orthogonality.

+1
source

Source: https://habr.com/ru/post/1433350/


All Articles