使用Thread.BeginCriticalRegion反射器,我发现SpinLock结构有很多调用.NET而不调用Thread.EndCriticalRegion.的情况例如,在公共函数SpinLock.Enter(ref bool lockTaken) (.NET 4.0)中:
// ...
Thread.BeginCriticalRegion();
if (Interlocked.CompareExchange(ref this.m_owner, managedThreadId, owner, ref lockTaken) == owner)
return; // <--- !!
Thread.EndCriticalRegion();
// ...在另一种情况下,Thread.EndCriticalRegion似乎没有调用Thread.BeginCriticalRegion.就调用了SpinLock.Exit
public void Exit(bool useMemoryBarrier)
{
if (this.IsThreadOwnerTrackingEnabled && !this.IsHeldByCurrentThread)
throw ...
if (useMemoryBarrier)
{
if (this.IsThreadOwnerTrackingEnabled)
Interlocked.Exchange(ref this.m_owner, 0);
else
Interlocked.Decrement(ref this.m_owner);
}
else if (this.IsThreadOwnerTrackingEnabled)
this.m_owner = 0;
else
{
int owner = this.m_owner;
this.m_owner = owner - 1;
}
Thread.EndCriticalRegion(); // <--- ??
}因此,问题是:是否有任何问题是由于不平衡开始/终止关键区域的调用而产生的?
发布于 2011-04-05 03:28:48
请注意,如果实际获取了锁,然后通过调用Exit()释放锁,则Begin/End调用将保持平衡。标记关键区域的调用是必要的,以便让CLR知道,当获得SpinLock时,线程中断可能会造成损害。有关更多信息,请参见这里。
https://stackoverflow.com/questions/5546797
复制相似问题