今天早上我在阅读源代码时遇到了一个我不理解的 C# 代码示例:
public bool Dequeue(out T value)
{
Node head;
Node tail;
Node next;
while (true)
{
// read head
head = this.head;
tail = this.tail;
next = head.Next;
// Are head, tail, and next consistent?
if (Object.ReferenceEquals(this.head, head))
{
// Source code continues here...
}
// And here...
}
}
我遇到问题的那一行包含 Object.ReferenceEquals()
。
如果我理解的很好,源代码作者想比较this.head
和head
,但是在上面的行中,他只是写了head = this。头
。
主要来自 C++
背景,这个说法对我来说毫无意义。此外,在某些情况下,Object.ReferenceEquals()
行似乎会抛出一个 System.NullReferenceException
,所以它确实做了一些事情,我只是想不通是什么。
你能帮我理解这条线的作用以及可能的原因吗?
如果您需要这个,这里是 Node
类定义(我猜它是一个"template"类,不确定 C# 的措辞):
private class Node
{
public T Value;
public Node Next;
public Node(T value)
{
this.Value = value;
}
}
谢谢。
编辑:方法的其余部分,对于那些提问的人
public void Enqueue(T value)
{
// Allocate a new node from the free list
Node valueNode = new Node(value);
while (true)
{
Node tail = this.tail;
Node next = tail.Next;
// are tail and next consistent
if (Object.ReferenceEquals(tail, this.tail))
{
// was tail pointing to the last node?
if (Object.ReferenceEquals(next, null))
{
if (Object.ReferenceEquals(
Interlocked.CompareExchange(ref tail.Next, valueNode, next),
next
)
)
{
Interlocked.CompareExchange(ref this.tail, valueNode, tail);
break;
}
}
else // tail was not pointing to last node
{
// try to swing Tail to the next node
Interlocked.CompareExchange<Node>(ref this.tail, next, tail);
}
}
}
}
最佳答案
看起来像一个链表。 Dequeue 看起来像一个递归函数。 因此,“Next”要么对节点的“head”部分执行某些操作,要么它并行运行,并且他试图在继续之前检查东西是否仍在原处。最后一部分做错了,因为你应该在进入关键部分时使用信号量,否则你会遇到竞争条件,它迟早会失败。
关于c# - 代码理解问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5167934/