Skip to content

std::osyncstream

Streaming to std::out from several threads in parallel regularly causes a mixture of the written text. (Nevertheless std::cout is thread safe, i.e. each single letter is safely written). For a synchronized output where text from several threads can be written without any disturbances by other thread output you can use std::osyncstream:

  • data streamed to a local osyncstream object go to a local buffer where they are safely collected
  • when the osyncstream object is destroyed, the buffer’s content is safely written to std::cout (or an other stream which was connected to osyncstream)
#include <syncstream>

void TestOSyncStream
{
    std::osyncstream syncStream(std::cout); // connect with standard output stream
    syncStream << "Write ";
    syncStream << "some ";
    syncStream << "data << "\n";

    // do something else

    // Destructor of syncStream automatically streams to std::cout
}
  • you can force writing to std::cout by calling osyncstream::emit():
std::osyncstream syncStream(std::cout); // connect with standard output stream
syncStream << "Write ";
syncStream << "some ";
syncStream << "data << "\n";
syncStream.emit(); // triggers synchronized streaming to std::cout
  • you can use a temporary object when streaming is done at a single location:
std::osyncstream(std::cout) << "Write some data\n";
// Temporary is destroyed here and causes synchronized streaming to std::cout