官术网_书友最值得收藏!

Interlocked internals

To understand how interlocked internals work under the hood, we're going to see what machine code is being generated when compiling the Interlocked.Increment method. If we just run the program in debug mode and look at the disassembly window, we will see the usual method call.

To see what is really going on, we have to enable all optimizations:

  1. First, we need to build the code in the Release mode in Visual Studio.
  2. Then, we have to go to Tools | Options | Debugging | General and uncheck the Suppress JIT optimization on module load option.
  3. Finally, add a System.Diagnostics.Debugger.Break() method call to pause the code in debugger.

If everything is set, you will see the following code in the disassembly window:

Interlocked.Increment(ref counter);

00007FFEF22B49AE  lea         rcx,[rsi+20h]
00007FFEF22B49B2  lock add    dword ptr [rcx],1

Note

Please notice the lock prefix in the last line of the code. This prefix is an instruction to the CPU to perform an atomic increment operation. This means that the Interlocked class is not a usual class, but a hint to the JIT compiler to generate a special code.

主站蜘蛛池模板: 海南省| 呼图壁县| 福清市| 鄱阳县| 常德市| 武夷山市| 乡宁县| 罗甸县| 汽车| 冕宁县| 长宁县| 兴和县| 庄河市| 安新县| 合肥市| 岳西县| 施秉县| 汶川县| 建水县| 介休市| 繁昌县| 安龙县| 忻城县| 公主岭市| 莱西市| 乌什县| 马鞍山市| 泸水县| 称多县| 扬州市| 临武县| 塘沽区| 万年县| 盐源县| 怀来县| 西贡区| 盖州市| 丁青县| 娱乐| 阳江市| 永城市|