Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@NoofSaeidh 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

This comment has been minimized.

Copy link
Owner Author

@retran retran commented Aug 8, 2018

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

@NoofSaeidh

This comment has been minimized.

Copy link

@NoofSaeidh NoofSaeidh commented Aug 10, 2018

@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