Skip to content

Instantly share code, notes, and snippets.

@Restuta
Created February 8, 2012 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Restuta/1772878 to your computer and use it in GitHub Desktop.
Save Restuta/1772878 to your computer and use it in GitHub Desktop.
find a thread safety bug
using System;
using System.Threading;
using System.Threading.Tasks;
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