Hasty Briefsbeta

Bilingual

C++ iostreams: Unexpected but legal multithreaded behaviour - Bert Hubert's writings

a day ago
  • Calling `std::ios_base::sync_with_stdio(false)` disables not only C stdio synchronization but also thread safety for standard iostream objects.
  • Tied streams (e.g., `cin` tied to `cout`) cause hidden write operations: reading from `cin` flushes `cout`, creating concurrent access even if only one thread directly writes to `cout`.
  • To avoid hidden concurrent writes in single-threaded `cout` usage, use `cin.tie(nullptr)` to break the tie.
  • Even synchronized streams can produce interleaved output; no atomicity guarantee for multiple `<<` operations, so user-level locking is needed for clean output.
  • The safest approach for multithreaded programs is to keep streams synchronized (i.e., avoid `sync_with_stdio(false)`) and protect all output with mutexes.