Advertisement

Forks and ofstream

Started by February 25, 2005 10:57 AM
5 comments, last by GameDev.net 19 years, 9 months ago
I'm getting errors when I try to write to a file from several threads. I'm using ofstream and making calls such as: fp << "This is a test"; from several threads simutaneously. My output looks like this: This is a Test This is a Tests a Test s a Test This is a TestTest This is a Test This is a Test I tried adding a fp.flush() call after every output statement, but the problem remains. Any idea of how to fix this?
Why do you think this behaviour is wrong? Is there any document that says it should behave different?
Advertisement
STL streams aren't thread-safe, so you'll have to do synchronization yourself.
thanks
Are you refering to a child process (as the title suggest) or a thread within one?
In the latter case you could always try protecting all access to the stream with a mutex.
However to guarantee consistent output from multiple processes you'd probably have to use a coordinating server.
well, what i figured out is that I just open the file with ios:app, the problem is solved. Before, each child process was left pointing to a different place in the file, which caused the unexpected overwrites.
Advertisement
NONE of the STL ( includes strings, streams, containers, etc ) is inherently thread-safe.

This topic is closed to new replies.

Advertisement