Re: Problems with output in a multithreaded program
Please keep in mind that three independent output functions are being
called in your code, unless you have locked all other threads from using
'out' they could interfere with that output.
Yes, I also used a mutex to send a message to 'out' in order to prevent
such conflicts. But it seems that is not the problem.
One possible problem might be that each thread has its own stream
object open on the same file. What typically happens is that each
stream is associated with some operating system open file handle which
has its own read/write pointer.
So the problem is not strictly a multithreading problem, but a problem
of multiple, independent, incoherent aliased views on the same file.
You could reproduce the same problem in a single threaded program. Open
a file twice with two stream objects. Write on one of them, then write
on the other. The second write will probably clobber the first.
Because this is not a threading problem, a mutex won't help. A mutex
does not help with the problem that two aliased, incoherent views of
the same file are being manipulated. That's not what a mutex is for.
In the UNIX filesystem, there is a special mode for keeping the
read-write pointer coherent, namely the append mode. The standard C
library has an "a" flag in fopen(), and C++ has ios::append. These
ought to map to this append mode if your operating system supports it.
In append mode, newly written data is atomically written to the end of
the file. Two processes that write to the same file through different
file descriptors that are both in append mode will not clobber each
But really, that is more intended for multi process programming: for
instance, two or more processes spewing debugging logs to the same
shared file. Within one program, there should be no reason (bad design
not being a valid reason!) why you should open the same file more than
once at the same time whether you are multithreading or not. If you
need to refer to the same file in two places, share the stream itself.
To protect that object properly under the presence of threads, see your
platform's programming documentation.