Search code examples
c++gccboostboost-iostreams

Standard way to implement a buffered stream that flushes at a constant interval?


I'm simulating packets from a source that produces packets at a given packet/second interval. I want to make a stream class that operates like an ostream object, allowing operator<< to be used to output things through it, but with the caveat that each value inserted should be released from the buffer to a file descriptor, in order, at a specified interval.

So, for instance, I might have a socket with file descriptor sockfd and say:

MyBuffer buffer(sockfd, 1000); //Interval of 1000 milliseconds
buffer << 1 << 2 << 3;

and the output would be timed such that it would output

1
<1 second gap>
2
<1 second gap>
3

to the socket. I'm looking at Boost.Iostreams right now, would that be a good solution? Is there some magical phrase I can google that describes this problem that I'm not aware of?

Any help would be appreciated.

Thanks Brad


Solution

  • One option for doing this that's completely orthogonal to building a custom streams class would be to maintain a queue of strings that's polled by a thread every second. Each time the queue is polled, the thread reads out the first element and sends it across the network.

    This doesn't use the streams library, but I think that might be what you want. Internally, most streams just glob together all the input they get into a mass of text, losing the information about which parts of the text correspond to each object you inserted.

    EDIT: I should have mentioned this the first time around, but please be sure to use the appropriate synchronization on this queue! You'll probably want to use a mutex to guard access to it, or to use a clever lock-free queue if that doesn't work. Just be sure not to blindly read and write to it from multiple threads.