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.
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.
. that locks a sema,
. writes to the file,
.create a fstream object if there is none
.open outstream object if it is not open
.write to the file
//close the file when the application terminates
. unlock sema.
This global function to be accessed from multiple files leading to concurrent invocations from multiple objects and threads.