0

let's say we have a piece of very simple code:

if (Interlocked.Exchange(ref m_ResourceInUse, 1) == 0) 
   return;

Interlocked.Exchange ensures that one thread changes m_resourceInUse from 0 to 1 and sees that m_resourceInUse was 0. This thread then returns.The other thread will change m_resourceInUse from a 1 to a 1. This thread will see that it did not change m_resourceInUse from a 0 ...

But "change m_resourceInUse from a 1 to a 1" is really unnecessary in hard ware level, CPU can ignore the instruction and do nothing, save some cycles that involves update register, main memory etc. So does Interlocked.Exchange changes m_resourceInUse from a 1 to a 1 or there is a special CPU instruction that can be mapped to not updating value if the condition is met?

sydevloper
  • 586
  • 8
  • Based on this [sharplab.io](https://sharplab.io/#v2:EYLgtghglgdgNAFxBAzmAPgAQAwAJMCMAdACoAWATgKYQAmsA5gNwCwAUO5gMz4BMuAYVwBvdrnG4ADhSgA3CAiq5YCXGAD6AJSooA9gFcKAYyoBJGAFUUSgLy5srNhNxiJ3fABZcAWQAUAShFXZ3EoADNcX3NFCgAbXSMAaypaIgBRAA8jMggYBipfagiNbT1DE3MrKjhcAkCbO2xA4JC3AHZHZwBfdi6gA) snippet, it does exchange values `xchg [ecx], eax`, some [details on `xchg` instruction](https://stackoverflow.com/a/50102807/997668). – Michael Jun 22 '21 at 06:20

0 Answers0