I was looking for an implementation for some parts of the .NET TPL "Dataflow" library out of curiosity, and I came across the following snippet:
private void GetHeadTailPositions(out Segment head, out Segment tail,
out int headLow, out int tailHigh)
{
head = _head;
tail = _tail;
headLow = head.Low;
tailHigh = tail.High;
SpinWait spin = new SpinWait();
while (
head != _head || tail != _tail
|| headLow != head.Low || tailHigh != tail.High
|| head._index > tail._index)
{
spin.SpinOnce();
head = _head;
tail = _tail;
headLow = head.Low;
tailHigh = tail.High;
}
}
(can be viewed here: https://github.com/dotnet/corefx/blob/master/src/System.Threading.Tasks.Dataflow/src/Internal/ConcurrentQueue.cs#L345 )
From what I understand regarding thread safety, this operation is subject to data race. I am going to explain my understanding, and then what I perceive as a βmistakeβ. Of course, I expect that this is more of a mistake in my mental model than in the library, and I hope that someone here can indicate where I am making a mistake.
...
(head, tail, head.Low tail.High) . :
, , :
ConcurrentQueue ( head, tail, head.Low tail.High).- .
- , 2
- , ""
, , , "" : . , (, head, tail).
, - head tail , / , CAS/spin.
, , . "" , , ? ""? : , , -, , , ?