I wonder how a std::osyncstream object prevents data race conditons? Does it lock some mutex?
I'm specifically talking about the below program:
#include <iostream>
#include <fstream>
#include <thread>
#include <syncstream>
void worker( const std::size_t startValue, const std::size_t stopValue, std::ostream& os )
{
for ( auto idx { startValue }; idx < stopValue; ++idx )
{
std::osyncstream out { os };
out << "thread: " << std::this_thread::get_id( ) << "; work: " << idx << '\n';
}
}
void runThreads( std::ostream& os )
{
std::jthread t1 { worker, 10000, 20000, std::ref( os ) };
std::jthread t2 { worker, 20000, 30000, std::ref( os ) };
}
int main( )
{
std::ofstream file { "out.txt" };
runThreads( file );
}
The source of the above code can be viewed here. Although I have made slight modifications to make it better and safer.
This simple program prints 20,000 lines into a file without generating a messy output.
The possible output:
thread: 2; work: 10000
thread: 3; work: 20000
thread: 2; work: 10001
thread: 2; work: 10002
thread: 2; work: 10003
thread: 2; work: 10004
thread: 2; work: 10005
thread: 2; work: 10006
.
.
.
What's going on behind the scenes? How do these two threads communicate with each other? Do they have separate copies of syncstream object? How does this object (i.e. out) manage the output stream os?