What is Interlocked.Increment actually doing?

我的未来我决定 提交于 2019-11-30 11:30:37

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.

I assume that it is an implementation detail, but one way to look at it is to inspect the JIT compiled code. Consider the following sample.

private static int Value = 42;
public static void Foo() {
   Interlocked.Increment(ref Value);
}

On x86 it generates the following

lock inc dword <LOCATION>

The lock modifier locks the bus to prevent multiple CPUs from updating the same data location.

On x64 it generates

lock xadd dword ptr <LOCATION>,eax

I would expect it to be a wrapper to the InterlockedIncrement64 Win32 API call.


EDIT: I see that it was a very short response. Building a little on it: It is easy to replicate the functionality of the function, but not the performance. There are native instructions in most CPUs that provide you with the atomic "Interlocked exchange and add" instruction, so you want that instruction to be used to implement your function, and I expect that the easiest way to achieve that from within C# would be to make the win32 API call. For more background on the subject, have a look at this whitepaper.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!