Skip to content

Instantly share code, notes, and snippets.

@jhgbrt
Last active May 22, 2017 16:11
Show Gist options
  • Save jhgbrt/57ca10ab7f29bf07630a58d01f4dfa81 to your computer and use it in GitHub Desktop.
Save jhgbrt/57ca10ab7f29bf07630a58d01f4dfa81 to your computer and use it in GitHub Desktop.
Which values can the variable 'x' have in the code below, and why? Hint: compile in release mode if you want to try it...
using System;
using System.Threading.Tasks;
namespace CodeQuiz
{
class Program
{
static void Main()
{
ulong sharedValue = 0;
var tasks = new[]
{
Task.Run(() =>
{
var v = true;
while (true)
{
sharedValue = v ? 0x0L : ulong.MaxValue;
v = !v;
}
}),
Task.Run(() =>
{
while (true)
{
var x = sharedValue;
Console.WriteLine($"x = {x:X16}");
}
})
};
var completed = Task.WaitAny(tasks);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment