Skip to content

Instantly share code, notes, and snippets.

@retran
Created August 7, 2018 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save retran/fa8c6b6671f0c91091a986a22d0f528b to your computer and use it in GitHub Desktop.
Save retran/fa8c6b6671f0c91091a986a22d0f528b to your computer and use it in GitHub Desktop.
using System;
using System.Threading.Tasks;
namespace MemoryReordering
{
class Program
{
private static int x;
private static int y;
private static int r1;
private static int r2;
private static void Foo()
{
x = 1;
r1 = y;
}
private static void Bar()
{
y = 1;
r2 = x;
}
static void Main(string[] args)
{
for (int i = 0; i < 10000; i++)
{
x = 0;
y = 0;
r1 = 0;
r2 = 0;
var t1 = Task.Run(() => Foo());
var t2 = Task.Run(() => Bar());
Task.WaitAll(t1, t2);
if (r1 == 0 && r2 == 0)
{
throw new InvalidOperationException("WTF???");
}
}
}
}
}
@NoofSaeidh
Copy link

NoofSaeidh commented Aug 8, 2018

The funny thing that it will not fail if start program only at 2 cores.

Oh, it fails but (often) needs more than 10k iterations :D

@retran
Copy link
Author

retran commented Aug 8, 2018

@NoofSaeidh It will never fail if you start it only at one core :)

@NoofSaeidh
Copy link

@retran of course. More cores more bugs! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment