Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sleep_for causes buffering effect

If I comment out the sleep_for, the program churns out commas and dots without issues. But when I add the sleep_for, it hangs for a while before suddenly writing all of the commas and dots you would have expected to come evenly during the hang all in one go.

This program was reduced to a minimum working example from something that was much larger and more complex, but fortunately the issue remains.

(Compiled using apt-installed g++ 11.2.0 on Ubuntu 20.04.4 LTS)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <chrono>
#include <iostream>
#include <RingBuffer.h>
#include <thread>

void writeCharToBuffer(volatile bool& quit, char, std::chrono::milliseconds);

int main()
{
    bool quit { false };

    using namespace std::literals;

    std::thread dotToBufferThread { writeCharToBuffer, std::ref(quit), '.', 100ms};
    std::thread commaToBufferThread { writeCharToBuffer, std::ref(quit), ',', 200ms};

    int quitKey;
    std::cin >> quitKey;
    quit = true;

    dotToBufferThread.join();
    commaToBufferThread.join();
}

void writeCharToBuffer(volatile bool& quit, char c, std::chrono::milliseconds d)
{
    while (!quit)
    {
        std::cout << c;
        std::this_thread::sleep_for(d);
    }
}

>Solution :

Output to std::cout is buffered.

It might be that the output without the delay will fill up the buffer quick enough that you won’t notice it.

If you want immediate output you need to explicitly flush it:

std::cout << c << std::flush;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading