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

  • 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.

主站蜘蛛池模板: 汪清县| 长岭县| 拉萨市| 色达县| 新沂市| 广西| 沙洋县| 漾濞| 虞城县| 澎湖县| 政和县| 乐业县| 梁山县| 新宾| 綦江县| 承德县| 宜阳县| 香格里拉县| 松江区| 防城港市| 马公市| 罗甸县| 合川市| 集贤县| 杭州市| 德安县| 台中县| 左贡县| 扶沟县| 邵阳市| 南昌县| 前郭尔| 中江县| 交口县| 乌拉特后旗| 内丘县| 灵川县| 海安县| 祥云县| 永吉县| 临猗县|