C++ iostreams: Unexpected but legal multithreaded behaviour

submited by
Style Pass
2021-11-25 19:30:10

In previous articles, I’ve waxed rhapsodic about how great C++ is. I also noted there however that every language, C++ included, has its dark sides. Some languages have an unavoidable pervasive dark side, like being slow or hard to multithread, for C++ that dark side is mostly its complexity. In this post I want to zoom in on a specific ‘gotcha’ that recently took me several hours to resolve. I wrote this piece so anyone running into the same issue might find out about it if they search the web.

You may end up at this page if your C++ programs suffer from duplicate output in multi-threaded programs, or unexpectedly corrupted output. This specifically after you’ve enabled the optimization std::ios_base::sync_with_stdio(false).

I want to thank Stackoverflow user bames53 for the insights found in his comment here. Thanks are also due to Stefan Bühler who first pointed out my bug was likely entirely legal behaviour.

Leave a Comment