以下是失败的集成测试的伪代码:
[测试]
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);
每次运行测试时,行数似乎都会发生变化。有时行数是 23,有时是 25。
在深入研究代码后,我注意到日志文件同时被多个线程访问(通过滴答计数相同来验证)。对此文件的访问没有锁定,但同时我没有看到抛出异常。谁能解释为什么运行之间的日志行数不一致?此外,这是多个线程同时写入同一个文件的负面影响吗?