Is operator<<(ostream&, obj) on two different streams thread safe? Is operator<<(ostream&, obj) on two different streams thread safe? multithreading multithreading

Is operator<<(ostream&, obj) on two different streams thread safe?


Update: I admit I didn't fully read the question before answering, so I took it upon myself to research this.

The TL;DR

There are mutable member variables here that could cause race condition. ios has static variables per locale, and these static variables lazy load (initialized when first needed) lookup tables. If you want to avoid concurrency problems, just be sure to initialize the locale prior to joining the threads so that any thread operation is read only to these lookup tables.

The Details

When a stream is initialized it populates a pointer which loads in the correct ctype for the locale (see _M_ctype):https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/basic_ios.h#L273

The error is referring to:https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/locale_facets.h#L875

This could be a race condition if two thread are simultaneously initializing the same locale.

This should be thread-safe (though it may still give error):

// Force ctype to be initialized in the base thread before forkingostringstream dump;dump << 1;auto runner = []() {    ostringstream oss;    for (int i=0; i<100000; ++i)        oss << i;};thread t1(runner), t2(runner);t1.join(); t2.join();


For 2 different streams it's thread safe :)