Skip to content

ablanchet/VolatileCheatSheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 

Repository files navigation

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;
  }
}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published