Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save miya2000/13286 to your computer and use it in GitHub Desktop.
Save miya2000/13286 to your computer and use it in GitHub Desktop.
C# concurrent test. (lock, Interlocked, ReaderWriterLock)
using System;
using System.Diagnostics;
using System.Threading;
namespace ConcurrentTest
{
class Program
{
const int CONCURRENT = 100;
const int LOOP = 100000;
static void Main(string[] args)
{
char mode = (args.Length == 0) ? (char)0 :
(args[0] == "-l") ? 'l' :
(args[0] == "-i") ? 'i' :
(args[0] == "-w") ? 'w' :
(char)1;
if (mode == 1)
{
throw new ArgumentException("-i or -l or -w");
}
int expected = CONCURRENT * LOOP;
int counter = 0;
ThreadStart ts = null;
if (mode == 0)
{
Console.WriteLine("unuse lock.");
ts = new ThreadStart(delegate
{
for (int j = 0; j < LOOP; j++)
{
counter++;
}
});
}
else if (mode == 'l')
{
Console.WriteLine("lock.");
object o = new object();
ts = new ThreadStart(delegate
{
for (int j = 0; j < LOOP; j++)
{
lock (o) { counter++; }
}
});
}
else if (mode == 'i')
{
Console.WriteLine("Interlocked.");
ts = new ThreadStart(delegate
{
for (int j = 0; j < LOOP; j++)
{
Interlocked.Increment(ref counter);
}
});
}
else if (mode == 'w')
{
Console.WriteLine("ReaderWriterLock lock.");
ReaderWriterLock rwLock = new ReaderWriterLock();
ts = new ThreadStart(delegate
{
for (int j = 0; j < LOOP; j++)
{
try
{
rwLock.AcquireWriterLock(Timeout.Infinite);
counter++;
}
finally
{
rwLock.ReleaseWriterLock();
}
}
});
}
Thread[] threads = new Thread[CONCURRENT];
for (int i = 0; i < threads.Length; ++i)
{
int ID = i;
threads[i] = new Thread(ts);
}
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < threads.Length; ++i)
{
threads[i].Start();
}
for (int i = 0; i < threads.Length; ++i)
{
threads[i].Join();
}
stopWatch.Stop();
Console.WriteLine("counter : {0:#,##0}", counter);
Console.WriteLine("expected: {0:#,##0}", expected);
Console.WriteLine("time: {0}(ms)", stopWatch.ElapsedMilliseconds);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment