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

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.

主站蜘蛛池模板: 怀仁县| 延长县| 长海县| 建阳市| 十堰市| 海南省| 和平区| 和田市| 琼中| 仪陇县| 沾化县| 太原市| 策勒县| 金坛市| 六盘水市| 调兵山市| 张家界市| 山阴县| 华宁县| 安国市| 岳阳县| 禹城市| 资阳市| 民勤县| 衡东县| 金山区| 龙川县| 甘泉县| 伽师县| 陵水| 河南省| 聊城市| 合川市| 平远县| 淄博市| 新竹县| 林口县| 鹤山市| 巴林右旗| 大理市| 迁安市|