Commits

Jordan Earls committed 5e11728

Added a crude, but better-than-nothing concurrency unit test. Everything appears to pass!

Comments (0)

Files changed (1)

CacheGen.Tests/GeneratedCodeTests.cs

 using System;
 using NUnit.Framework;
 using System.Linq;
+using System.Threading;
 
 namespace Earlz.CacheGen.Tests
 {
 
 		}
 
+		[Test]
+		public void ConcurrencyTest()
+		{
+			long runtime=1000 * 10000; //ticks (milliseconds * 100ns)
+			int insanity=10; //number of threads to spawn of each function
+			//var randomread=new Random();
+			//var randomwrite=new Random();
+			Exception monkeycatch=null;
+			ThreadStart monkey=()=> //the thing that screws up our cache
+			{
+				try
+				{
+					lock(Cacher) //lock here because I'm sure .Clear isn't thread safe
+					{
+						Cacher.Reset();
+					}
+					lock(TestCache.testdictionary)
+					{
+						TestCache.testdictionary.Clear();
+					}
+					Thread.Sleep(10);
+				}
+				catch(Exception e)
+				{
+					monkeycatch=e;
+				}
+			};
+			Exception writecatch=null;
+			ThreadStart write = ()=>
+			{
+				try
+				{
+					while(true)
+					{
+						TestCache.Testfoo=new string('c', 20);
+						TestCache.testdictionary[1]=new string('d', 20);
+						TestCache.testdictionary[20]=new string('9', 20);
+					}
+				}
+				catch(Exception e)
+				{
+					writecatch=e;
+				}
+			};
+			Exception readcatch=null;
+			ThreadStart read = () =>
+			{
+				try
+				{
+					while(true)
+					{
+						string tmp=TestCache.testdictionary[1];
+						tmp=TestCache.Testfoo;
+						tmp=TestCache.testdictionary[20];
+					}
+				}
+				catch(Exception e)
+				{
+					readcatch=e;
+				}
+			};
+			var monkeythreads=new Thread[insanity];
+			var readthreads=new Thread[insanity];
+			var writethreads=new Thread[insanity];
+			for(int i=0;i<insanity;i++)
+			{
+				monkeythreads[i]=new Thread(monkey);
+				readthreads[i]=new Thread(read);
+				writethreads[i]=new Thread(write);
+
+			}
+			long ms=DateTime.Now.Ticks;
+			for(int i=0;i<insanity;i++)
+			{
+				monkeythreads[i].Start();
+				readthreads[i].Start();
+				writethreads[i].Start();
+			}
+			while(DateTime.Now.Ticks < ms+runtime)
+			{
+				Thread.Sleep(10);
+			}
+			if(readcatch!=null)
+			{
+				throw readcatch;
+			}
+			if(writecatch!=null)
+			{
+				throw writecatch;
+			}
+			if(monkeycatch!=null)
+			{
+				throw monkeycatch;
+			}
+			for(int i=0;i<insanity;i++)
+			{
+				readthreads[i].Abort();
+				writethreads[i].Abort();
+				monkeythreads[i].Abort();
+			}
+		}
+
 
 	}
 }