I need to write to a file from multiple objects, out of which few objects spawn multiple threads.

Can any one give me some tips.


Recommended Answers

All 6 Replies

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.

Thanks for the suggestions.
I'm worried about extensive use of semaphores.
I've already used few semaphores elsewhere, and worried about avoiding deadlock scenarios.

I've an alternative thought, how abt writing with cout and redirecting the output to a file? Would the problems associated with normal file also present here?

redirecting cout to a file would solve nothing. maybe you can use an existing semaphore instead of creating yet another one.

Ok. I'll try reusing the semaphore.

I've come across a code piece wherein one fstream object and one ofstream* are used as data members in the class providing the writing to log functionality?

I could not understand why do we need fstream object, where the purpose is only to write to the file.

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.


Can you please comment on the below approach?

1. A global function

. 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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.