Table of Contents

<syncstream>

<syncstream> provides std::osyncstream, a wrapper around std::ostream that buffers output and flushes it atomically, preventing interleaved writes from multiple threads (C++20).

Use it when multiple threads write to the same stream and you want each logical message to be atomic.

Example

This example uses osyncstream from multiple threads to write atomic messages to stdout without interleaving.

// compile: g++ -std=c++20 -pthread -o syncstreamexample syncstreamexample.cpp
// run: ./syncstreamexample
// description: synchronized output from multiple threads
 
#include <syncstream>
#include <iostream>
#include <thread>
 
int main() {
    std::osyncstream out(std::cout);
 
    auto worker = [](int id) {
        std::osyncstream local(std::cout);
        local << "thread " << id << " message\n";
    };
 
    std::thread t1(worker, 1);
    std::thread t2(worker, 2);
 
    t1.join();
    t2.join();
 
    return 0;
}