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

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

主站蜘蛛池模板: 化隆| 连平县| 芒康县| 阳原县| 平江县| 富阳市| 蒲城县| 无棣县| 福海县| 利辛县| 台湾省| 新绛县| 来安县| 南川市| 梅河口市| 鲁甸县| 平乡县| 太仓市| 松潘县| 灯塔市| 凤阳县| 汾阳市| 嘉义市| 盈江县| 达日县| 清苑县| 大安市| 三门县| 鸡西市| 澎湖县| 沙雅县| 蓝田县| 芦山县| 汕尾市| 金塔县| 西林县| 大石桥市| 花莲县| 南部县| 肥城市| 军事|