The following is pseudo code of an integration test that is failing:
[Test]
void TestLogger()
// Init static logger
Logger.Init(pathToFile);
// Create five threads that will call LogMessages delegate
for i = 1 to 5
{
Thread aThread = new Thread(LogMessages)
aThread.Start(i);
}
// let threads complete their work
Thread.Sleep(30000);
/// read from log file and count the lines
int lineCount = GetLineCount();
// 5 threads, each logs 5 times = 25 lines in the log
Assert.Equal(25, lineCount);
static void LogMessages( object data )
// each thread will log five messages
for i = 1 to 5
Logger.LogMessage(i.ToString() + " " + DateTime.Now.Ticks.ToString());
Thread.Sleep(50);
The number of lines seem to change each time the test is run. Sometimes the number of lines is 23 and sometimes 25.
After I dug through the code a little bit, I noticed that the log file is getting accessed at the same time by multiple threads (verified by tick count being the same). There is no lock around the access to this file, but at the same time I see no exceptions being thrown. Can anyone explain why the log line count between runs is inconsistent? Furthermore, is this a negative effect of writing to the same file by multiple threads at the same time?
Race conditions, as you have here, are notoriously unpredictable. You never know how many writes won’t work properly – it might even work completeely fine, sometimes. And yes, this is a negative effect of writing to the same file from multiple threads without synchronization.