我正在阅读source codes for ConcurrentQueue,这时我看到了这个(第790-811行):
//We need do Interlocked.Increment and value/state update in a finally block to ensure that they run
//without interuption. This is to prevent anything from happening between them, and another dequeue
//thread maybe spinning forever to wait for m_state[] to be true;
try
{ }
finally
{
newhigh = Interlocked.Increment(ref m_high);
if (newhigh <= SEGMENT_SIZE - 1)
{
m_array[newhigh] = value;
m_state[newhigh].m_value = true;
}
//if this thread takes up the last slot in the segment, then this thread is responsible
//to grow a new segment. Calling Grow must be in the finally block too for reliability reason:
//if thread abort during Grow, other threads will be left busy spinning forever.
if (newhigh == SEGMENT_SIZE - 1)
{
Grow();
}
}在读完那条评论后,我仍然不知道它是什么意思。finally块有什么魔力,官方API会把一个代码块包装到一个有一个空try块的finally块中?有没有一个简单的例子可以解释finally块的这种特殊功能?
发布于 2019-11-12 15:01:37
当finally块正在运行时,不能发生线程中止。您可以通过CLR保证执行。
您发布的代码正在利用这一事实来确保始终执行清理。
https://stackoverflow.com/questions/58813395
复制相似问题