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

  • Mastering C# Concurrency
  • Eugene Agafonov Andrew Koryavchenko
  • 185字
  • 2021-07-09 21:26:07

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.

主站蜘蛛池模板: 社旗县| 陆河县| 龙江县| 怀远县| 九龙县| 兴安县| 大田县| 吴桥县| 中方县| 偏关县| 赫章县| 丽水市| 尚义县| 邓州市| 久治县| 惠来县| 阿拉善盟| 田东县| 宁河县| 株洲县| 江阴市| 梁山县| 昌平区| 金湖县| 甘南县| 塔城市| 崇礼县| 西贡区| 错那县| 洞口县| 博罗县| 崇左市| 永丰县| 宣武区| 革吉县| 万全县| 铜梁县| 诏安县| 杭锦后旗| 黑山县| 镶黄旗|