I read the source code this morning when I came across a sample C # code that I don't understand:
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... } }
On line, I have a problem with what Object.ReferenceEquals() contains.
If I understand well, the author of the source code wants to compare this.head and head , but in the lines above, he simply wrote head = this.head .
Based on the background of C++ , this statement makes no sense to me. Moreover, on some events, it seems that the Object.ReferenceEquals() throws a System.NullReferenceException , so it is doing something, I just canβt understand that.
Can you help me understand what this line does and maybe why?
If you need it, here is the definition of the Node class (I think this is the "template" class, not sure about the wording for C #):
private class Node { public T Value; public Node Next; public Node(T value) { this.Value = value; } }
Thanks.
Edit: the rest of the method for those who asked
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); } } } }