Fix several comparison issues in ConcurrentBag (dotnet/corefx#38424)
authorStephen Toub <stoub@microsoft.com>
Tue, 11 Jun 2019 15:34:32 +0000 (08:34 -0700)
committerGitHub <noreply@github.com>
Tue, 11 Jun 2019 15:34:32 +0000 (08:34 -0700)
commit409a1fb1623333649a5a8b9e5d113d6faadd0776
tree7037ea7273434ecd520551809936eecbe1a347dc
parentd733ef7f770892ba929d8e0f1ca9c03cdaebe67a
Fix several comparison issues in ConcurrentBag (dotnet/corefx#38424)

A failed assert now and again in CI highlighted that we weren't properly accounting for overflows in ConcurrentBag.  In a variety of cases we compare the head position to the tail position, e.g. `head < tail` to determine if there are items in the queue, but in some situations when a position is temporarily updated, head can temporarily progress beyond tail, and if it does and wraps around due to overflow, we can end up in a situation where the condition passes even though it shouldn't.  This fixes all of the comparisons to do the subtraction and compare to 0, to avoid the overflow issue.

Separately, TrySteal had an inverted condition that was checking whether the queue contained at least 2 elements rather than checking whether it contained <= 2.  Also fixed that by inverting the check, along with doing the comparison appropriately per the above.

Commit migrated from https://github.com/dotnet/corefx/commit/56496a6dc2583db7ec82e779235813e0b8d32611
src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentBag.cs
src/libraries/System.Collections.Concurrent/tests/ConcurrentBagTests.netcoreapp.cs