Home > Uncategorized > +=1, -=1 not atomic operations at VB.net

+=1, -=1 not atomic operations at VB.net

This is something that bit me sometime ago: seems +=1 and -=1 aren’t atomic operations at VB.net and other .NET languages (not sure for C++) although modern CPUs have INC and DEC instructions at least for integers (maybe IL – intermediate language [for .NET compilers’ target "theoretical" machine spec] – doesn’t define such?)
You have to use the class System.Threading.Interlocked and specifically the Increment and Decrement methods it has (you can pass an integer ByRef to them for example to do say i+=1 and i-=1 in a thread-safe way). That class also has methods to Add/Subtract more than 1 (haven’t checked if it also support multiplications/divisions etc.)
Many thanks to the guy who tiped me about this at a Microsoft Hellas presentation some years ago in Athens, wouldn’t have spotted that class myself, although I was already skeptical whether +=1 and -=1 were atomic operations (thread-safe, fetch and update done in 1 step) in VB.net and other .NET languages or not and was querying about it some MS Hellas people (who didn’t know either – I even asked J# program manager sometime ago and they had to doublecheck to be totally sure it didn’t do it as atomic operation either)
I wonder about what C++ compiler does on .NET regarding this one, I though the ANSI C++ spec said += and -= are atomic, but I might be remembering wrong
Categories: Uncategorized Tags:
  1. Igor
    2008/01/29 at 15:46

    The INC & DEC instructions are available since the 8088 CPU (and I suppose these were not the first chips with these instructions). The generated IL code has less in common with the CPU opcodes generated at runtime because of the optimization. And I would expect that  the generated code does use the INC & DEC CPU instructions.IMHO, the problem is in CPU\’s cache. It wouldn\’t immediately write the changed value to the memory, but keep it in it\’s cache. And here are the problems you mentioned. The Interlocked class ensures appropriate handling of those operations.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: