// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Threading; using NUnit.Framework; [TestFixture] public class MultiTestTest { [SetUp] protected void Init() { } [TearDown] protected void Dispose() { } private const int NCALL = 1000; private const int MAXTHREADS = 100; private const double MAXTIME = 0.0000005; [Test] public void Multi() { (new T(NCALL)).Run(); // warmup for(int nthreads = 1; nthreads <= MAXTHREADS; nthreads++) { long t1 = DateTime.Now.Ticks; T[] o = new T[nthreads]; Thread[] t = new Thread[nthreads]; for(int i = 0; i < nthreads; i++) { o[i] = new T(NCALL); t[i] = new Thread(new ThreadStart(o[i].Run)); } for(int i = 0; i < nthreads; i++) { t[i].Start(); } for(int i = 0; i < nthreads; i++) { t[i].Join(); Assert.AreEqual(NCALL, o[i].Good, "Thread " + i + "/" + nthreads); } long t2 = DateTime.Now.Ticks; Assert.IsTrue((t2 - t1) / 100000000.0 / nthreads / NCALL < MAXTIME, "Time with " + nthreads + " threads"); } } } public class T { private int total; private int good; public T(int total) { this.total = total; good = 0; } public void Run() { Test tst = new Test(); for(int i = 0; i < total; i++) { if(tst.Dup("abc") == "abcabc") good ++; } } public int Good { get { return good; } } }