下面是一个集成测试失败的伪代码:多线程写入同一文件时会发生什么负面影响?
[测试]
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。
当我通过代码挖了一点之后,我发现日志文件被多个线程同时访问(通过tick计数是相同的) 。对这个文件的访问没有任何锁定,但同时我没有看到抛出异常。任何人都可以解释为什么运行之间的日志行数不一致吗?此外,这是多线程同时写入同一文件的负面影响吗?
要添加到上面的答案,如果线程1获取A,并将B添加到A.然后线程2进来并获取A,将C添加到它。线程1将AB保存到文件,但因为线程2已经读取了文件,所以当它重写文件时,文件将只包含AC而不是ABC。 – 2012-07-05 17:40:42