Skip to content

Instantly share code, notes, and snippets.

@jchannon
Created February 28, 2012 09:38
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 jchannon/1931579 to your computer and use it in GitHub Desktop.
Save jchannon/1931579 to your computer and use it in GitHub Desktop.
Thread Safety
for (int i = 0; i < 100; i++)
{
ManualResetEvent allGo = new ManualResetEvent(false);
var model = new MyClass();
object starter = new object();
int waiting = 20;
int failures = 0;
Exception firstException = null;
Thread[] threads = new Thread[20];
for (int j = 0; j < 10; j++)
{
threads[2 * j] = new Thread(() =>
{
try
{
if (Interlocked.Decrement(ref waiting) == 0) allGo.Set();
allGo.WaitOne();
model.Add(i.ToString());
}
catch (Exception ex)
{
Interlocked.CompareExchange(ref firstException, ex, null);
Interlocked.Increment(ref failures);
}
});
threads[(2 * j) + 1] = new Thread(() =>
{
try
{
if (Interlocked.Decrement(ref waiting) == 0) allGo.Set();
allGo.WaitOne();
model.Add(i.ToString());
}
catch (Exception ex)
{
Interlocked.CompareExchange(ref firstException, ex, null);
Interlocked.Increment(ref failures);
}
});
}
for (int j = 0; j < threads.Length; j++) threads[j].Start();
for (int j = 0; j < threads.Length; j++) threads[j].Join();
Assert.IsNull(firstException);
Assert.AreEqual(0, Interlocked.CompareExchange(ref failures, 0, 0));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment