Only one object and one thread can write to a file at one time. The reason should be obvious -- if two threads attempt to write to the file at the same time the result will be an unpredictible mixture of the data. You can take at least a couple approaches to the problem
1. create one function that does all the writing. All objects/threads pass write requests to that one function.
2. Synchronize access to the file -- most commonly use a semiphore for that purpose. A semiphone is an operating system resource that blocks threads when it is in use by another thread.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
redirecting cout to a file would solve nothing. maybe you can use an existing semaphore instead of creating yet another one.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
I could not understand why do we need fstream object, where the purpose is only to write to the file.
because the program can't write to a file without it. It probably opens the file once and leaves it open for a very long time, and passes the fstream object around to other methods in the class. I don't like leaving a file open for long periods of time -- my logging function closes the stream as quickly as possible to (1) reduce possibility of corrupt file in case of abnormal termination of the program and (2) other programs, processes and people can easily access the file.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343