在编写单元测试时,我偶然发现了 ReaderWriterLock 的一个非常奇怪的问题。我尝试使用设置为 50 毫秒的超时选项来测试 UpgradeToWriterLock 方法。
在主线程上,我获取阅读器锁,然后启动许多任务。在任务上,我也使用读卡器锁定,然后尝试在超时的情况下升级到写器。这应该在每一个上都失败,因为主线程正在持有读锁。由于超时为 50 毫秒,因此任务应抛出超时异常并完成。如果我开始超过 10 项任务,他们不会。他们卡在 UpgradeToWriterLock 上。
谁能解释一下?整个源代码如下。
[TestMethod]
public void UpgradeLockFailTest()
{
// strangely when more than 10 threads then it gets stuck on UpgradeToWriterLock regardless of the timeout
const int THREADS_COUNT = 20;
// 50 milliseconds
const int TIMEOUT = 50;
// create the main reader writer lock
ReaderWriterLock rwl = new ReaderWriterLock();
// acquire the reader lock on the main thread
rwl.AcquireReaderLock(TIMEOUT);
// create and start all the tasks
Task[] tasks = new Task[THREADS_COUNT];
for (int i = 0; i < THREADS_COUNT; i++)
{
tasks[i] = Task.Factory.StartNew(() =>
{
try
{
// acquire the reader lock on the worker thread
rwl.AcquireReaderLock(TIMEOUT);
// acquire the writer lock on the worker thread
rwl.UpgradeToWriterLock(TIMEOUT); // <-- GETS STUCK HERE AND DOESN'T RESPECT TIMEOUT
}
finally
{
rwl.ReleaseLock();
}
});
}
// should be enough for all the tasks to be created
Thread.Sleep(2000);
try
{
// wait for all tasks
Task.WaitAll(tasks); // <-- GETS STUCK HERE BECAUSE THE TASKS ARE STUCK ON UpgradeToWriterLock
}
catch (AggregateException ae)
{
Assert.AreEqual(THREADS_COUNT, ae.InnerExceptions.Count);
}
// release all the locks on the main thread
rwl.ReleaseLock();
}
有趣的是,如果我在等待任务之前释放主线程读取器锁,一切都会按预期工作。抛出正确数量的超时异常。