-
-
Save chaliy/1837799 to your computer and use it in GitHub Desktop.
find a thread safety bug
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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