Home > Back-end >  sleep_for causes buffering effect
sleep_for causes buffering effect

Time:04-06

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)

#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);
    }
}

CodePudding user response:

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;
  • Related