C
Cool Guy
I have an application log file class which is used throughout the app,
potentially by multiple threads. It's a singleton.
Here're the relevant parts:
sealed class LogFile
{
#region Singleton functionality
public static readonly LogFile Instance = new LogFile();
static LogFile() {
}
#endregion
StreamWriter streamWriter;
readonly object streamWriterLock;
LogFile() {
#if TRACE
streamWriterLock = new Object();
FileStream fileStream = File.Open(...);
lock (streamWriterLock) { // lock for write memory barrier
// (not sure whether this is needed)
streamWriter = new StreamWriter(fileStream, Encoding.ASCII);
}
#endif
}
public void AddEntry(string text) {
#if TRACE
lock (streamWriterLock) {
streamWriter.WriteLine(text);
streamWriter.Flush();
}
#endif
}
}
Now, obviously I lock in AddEntry for atomic writing to the file.
But my question is: should /streamWriterLock/ be volatile?
There could be a situation where, for example, thread A and thread B are
both running, and thread A accesses Instance thus creating the instance.
Then thread B accesses it. Would thread B definitely see the right value
for /streamWriterLock/ in this case?
potentially by multiple threads. It's a singleton.
Here're the relevant parts:
sealed class LogFile
{
#region Singleton functionality
public static readonly LogFile Instance = new LogFile();
static LogFile() {
}
#endregion
StreamWriter streamWriter;
readonly object streamWriterLock;
LogFile() {
#if TRACE
streamWriterLock = new Object();
FileStream fileStream = File.Open(...);
lock (streamWriterLock) { // lock for write memory barrier
// (not sure whether this is needed)
streamWriter = new StreamWriter(fileStream, Encoding.ASCII);
}
#endif
}
public void AddEntry(string text) {
#if TRACE
lock (streamWriterLock) {
streamWriter.WriteLine(text);
streamWriter.Flush();
}
#endif
}
}
Now, obviously I lock in AddEntry for atomic writing to the file.
But my question is: should /streamWriterLock/ be volatile?
There could be a situation where, for example, thread A and thread B are
both running, and thread A accesses Instance thus creating the instance.
Then thread B accesses it. Would thread B definitely see the right value
for /streamWriterLock/ in this case?