Skip to content

Latest commit

 

History

History
109 lines (96 loc) · 2.06 KB

readme.md

File metadata and controls

109 lines (96 loc) · 2.06 KB

Instructions reordering

Instructions types C# x86 C# volatile
LoadStore ✔️
LoadLoad ✔️
StoreStore
StoreLoad ✔️ ✔️ ✔️

Fencing

Full fence

public void Method()
{
  ... instruction ...
  ... instruction ...
  ... instruction ...
  Thread.MemoryBarrier(); -----------------
  ... instruction ...
  ... instruction ...
  ... instruction ...
}

full fence

Half fence : volatile read : acquire fence

💡 ARF = Acquire Read Follow

private volatile int _value;

public void Method()
{
  ... instruction ...
  ... instruction ...
  ... instruction ...
  if (_value) -----------------
  {
    ...
  }
  ... instruction ...
  ... instruction ...
  ... instruction ...
}

read fence

Half fence : volative write : release fence

private volatile int _value;

public void Method()
{
  ... instruction ...
  ... instruction ...
  ... instruction ...
  _value = 1;  -----------------
  ... instruction ...
  ... instruction ...
  ... instruction ...
}

write fence

Example

public class X 
{
  private volatile int _continue;
  
  public void Run()
  {
    _continue = 0;
    while (_continue == 0)
    {
      ...
    }
  }
  
  public void Stop()
  {
    _continue = 1;
  }
}

In this case if _continue is not defined as volatile and if Run() and Stop() are called from different threads and if the compiler wants to reorder some lines or if CPU wants to reorder the instructions we can have something like this :

public class X 
{
  private int _continue;
  
  public void Run()
  {
    _continue = 0;
    if (_continue != 0)
      return;
    
    while (true)
    {
      ...
    }
  }
  
  public void Stop()
  {
    _continue = 1;
  }
}