Search code examples
c#multithreadinginterlocked

What is Interlocked.Increment actually doing?


Interlocked.Increment seems like among the most standard/simple of operations one would need to perform in multithreaded code.

I assume that the functionality of the method is some sort pattern that anyone with threading experience would be able to replicate.

So basically what I am wondering is if someone could provide an exact duplicate (with explanation of how it works) of what the Interlocked.Increment method is actually doing internally? (I have looked for the source of the actual method but been unable to find it)


Solution

  • According to Mr Albahari it does two things:

    • makes the atomicity of the operation known to the OS and VM, so that e.g. operations on 64bit values on 32bit system will be atomic
    • generates full fence restricting reordering and caching of the Interlocked vars

    Have a look at that link - it gives some nice examples.