I was looking at the ConcurrentBag documentation page, and the code sample they provided has the following:
itemsInBag
is a plain int
, and it is written to concurrently without synchronization. This looks like a race condition, unless I’m missing something.
You’re right. Click the “edit” link on top right of the page and submit a PR to fix. It should be using Interlocked.Increment
.
Correct, ++ is not threadsafe.
This looks like a race condition, unless I’m missing something.
That’s only relevant if you access the result while within the loop (which the code doesn’t), in which case you should use Interlocked.Increment.
“++” increment operator is not atomic, so in effect you are accessing the result. I believe OP is correct and this would indeed be a race condition. In fact, it’s the same problem shown for the example of a software race conditions on Wikipedia – https://en.wikipedia.org/wiki/Race_condition#Software
Could you elaborate? ++
is both a read and write operation, so it does access the result within the loop.
Disagree. The Task.Run and bagConsumeTask.Add might be faster than TryTake and especially Console.WriteLine (which is blocking!), so there might be multiple concurrent increment operations running.