Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
i develop a class to write logs. it writes with "StreamWriter.WriteLine()" function.

logStream.WriteLine(msgWrite);
logStream.Flush();

some different threads use this class to write logs, in one text file(The log file is common for all threads) do it need to lock() function?

should i change my code?

lock(syncObj)
{
logStream.WriteLine(msgWrite);
logStream.Flush();
}

please help me.
Posted

1 solution

Yes it needs lock,

How a data write to a stream :

Stream is a pointer which holds some memory now when we write data to file stream data would first store into buffer and then flush to your memory now in between that if two or more threads are working simultaneously then buffer may be replaced by the new data and your file data may show mixed lines.
Because buffer will change on demand and it dose not ensure the data is properly written to the file or not its just a intermediate data holder.

Now lock will come to play for providing synchronized access of file pointers until one thread release the that buffer or complete job on that stream other will wait so there is no data damaged will occur.

Happy Coding...
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 16-Sep-14 0:56am    
Correct, a 5.

To OP: lock-free programming is something different: avoiding using shared data, using calculations on stack, and so on.
What you are trying to do is not lock-free in first place, by the very nature of your algorithm...

—SA
Suvabrata Roy 16-Sep-14 0:57am    
Thanks...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900