Skip to content

Instantly share code, notes, and snippets.

@chaliy
Forked from Restuta/gist:1772878
Created February 15, 2012 17:58
Show Gist options
  • Save chaliy/1837799 to your computer and use it in GitHub Desktop.
Save chaliy/1837799 to your computer and use it in GitHub Desktop.
find a thread safety bug
using System;
using System.Threading;
using System.Threading.Tasks;
# Test
namespace ConsoleApplication3
{
class ThreadUnsafe
{
public static int _val1 = 1;
public static int _val2 = 1;
private static readonly object syncObj = new object();
public void Go()
{
lock (syncObj)
{
if (_val2 != 0)
{
Thread.Sleep(0);
var i = _val1/_val2;
}
}
_val2 = 0;
}
}
class Program
{
static void Main(string[] args)
{
ThreadUnsafe threadUnsafe1 = new ThreadUnsafe();
ThreadUnsafe threadUnsafe2 = new ThreadUnsafe();
for (int i = 0; i < 10000; i++)
{
Task task = new Task(threadUnsafe1.Go);
Task task1 = new Task(threadUnsafe2.Go);
task.Start();
task1.Start();
try
{
Task.WaitAll(task, task1);
}
catch (AggregateException ex)
{
Console.WriteLine(i);
Console.WriteLine(ex);
}
ThreadUnsafe._val2 = 1;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment