| Instructions types | C# | x86 | C# volatile |
|---|---|---|---|
| LoadStore | ✔️ | ❌ | ❌ |
| LoadLoad | ✔️ | ❌ | ❌ |
| StoreStore | ❌ | ❌ | ❌ |
| StoreLoad | ✔️ | ✔️ | ✔️ |
publicvoidMethod(){
...instruction ...
...instruction ...
...instruction ...Thread.MemoryBarrier();-----------------
...instruction ...
...instruction ...
...instruction ...}💡 ARF = Acquire Read Follow
privatevolatileint_value;publicvoidMethod(){
...instruction ...
...instruction ...
...instruction ...if(_value)-----------------{
...}
...instruction ...
...instruction ...
...instruction ...}privatevolatileint_value;publicvoidMethod(){
...instruction ...
...instruction ...
...instruction ..._value=1;-----------------
...instruction ...
...instruction ...
...instruction ...}publicclassX{privatevolatileint_continue;publicvoidRun(){_continue=0;while(_continue==0){
...}}publicvoidStop(){_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 :
publicclassX{privateint_continue;publicvoidRun(){_continue=0;if(_continue!=0)return;while(true){
...}}publicvoidStop(){_continue=1;}}

