Static volatile fields on .net framework #48884
-
It seems that "B" field will be loaded before "A". It is true? I am wondering because it seems there is reordering here even though A is marked as volatile. using System;
using System.Threading;
public class Program
{
public static volatile int A;
public static int B;
public bool ReadAndCheck()
{
var a = A;
var b = B;
return a > b;
}
}
// AMD 64
Program.ReadAndCheck()
L0000: mov eax, [rip+0xa269a]
L0006: cmp [rip+0xa2690], eax
L000c: setg al
L000f: movzx eax, al
L0012: ret in .net core both fields are loaded into registers csharplab .net core You can play around with it using System;
using System.Threading;
public class Program
{
public static volatile int A = 1;
public static int B = 1;
public static bool ReadAndCheck()
{
var a = A;
var b = B;
return a > b;
}
public static void First()
{
while (true)
{
e.WaitOne();
if (ReadAndCheck())
{
Console.WriteLine("reordering");
}
e.Set();
}
}
private static AutoResetEvent e;
public static void Second()
{
while (true)
{
A = 1;
B = 1;
e.Set();
B = 2;
A = 2;
e.WaitOne();
}
}
public static void Main()
{
e = new AutoResetEvent(false);
new Thread(First).Start();
new Thread(Second).Start();
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
danmoseley
Mar 5, 2021
Replies: 1 comment 7 replies
-
Cc @stephentoub |
Beta Was this translation helpful? Give feedback.
7 replies
Answer selected by
eterekhin
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cc @stephentoub