Search code examples
cmultithreadingposixstderr

Writing to stderr using write() from thread


In a Qt/C++ application I need to use write() to print some text to stderr. I'm doing something like this multiple times:

  write(stdErrDescriptor, "H", 1);
  write(stdErrDescriptor, "e", 1);
  write(stdErrDescriptor, "l", 1);
  write(stdErrDescriptor, "l", 1);
  write(stdErrDescriptor, "o", 1);
  write(stdErrDescriptor, "\n", 1);

I'm calling that from the main thread and a sub thread. The output of the threads should be serialized by internal program logic. This means the main thread should not print at the same time as the sub thread. This seems to be true since in reality I could never see interleaved lines on the console. Still there is something going on that I do not understand.

I expected to see something like this:

Hello
Hello
Hello
Hello
Hello
Hello

However I get this:

Hello
Hello
H
e
l
l
o

H
e
l
l
o

Hello
Hello

Please note that lines are not interleaved. Still a line feed is added after each write() call when executing the code snippet from a sub thread.

The effect is completely reproducible when starting the debug build from Qt Creator under gdb supervision. However when manually stepping through the code or when running the debug build without debugger the output looks just fine.

I'm running the code on Kubuntu 20.04 and GCC 12.

What is going on?


Solution

  • This is a bug: https://bugreports.qt.io/browse/QTCREATORBUG-29100

    The problem can also be reproduced with no threads involved.