Example #1
0
        private static long ExerciseCounter(Counter counter, int nThreads, int nIncrements)
        {
            Task[] threads = new Task[nThreads];
            Stopwatch sw = Stopwatch.StartNew();
            for (int nThread = 0; nThread < threads.Length; nThread++)
            {
                threads[nThread] = Task.Factory.StartNew(() =>
                {
                    for (int nIteration = 0; nIteration < nIncrements; nIteration++)
                    {
                        counter.Increment();
                    }
                });
            }

            Task.WaitAll(threads);
            sw.Stop();
            return sw.ElapsedMilliseconds;
        }
        public static void Main()
        {
            Console.WriteLine("\n\nUnsafe test:");
            asyncOpsAreDone.Reset();
            numAsyncOps = totalNumberOfAsyncOps;
            counter = new CounterUnsafe();
            for (int threadNum = 0; threadNum < numAsyncOps; threadNum++)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(UpdateResource), threadNum);
            }
            asyncOpsAreDone.WaitOne();
            Console.WriteLine("All Unsafe threads have completed.");

            Console.WriteLine("\n\nLock test:");
            asyncOpsAreDone.Reset();
            numAsyncOps = totalNumberOfAsyncOps;
            counter = new CounterUsingLock();
            for (int threadNum = 0; threadNum < numAsyncOps; threadNum++)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(UpdateResource), threadNum);
            }
            asyncOpsAreDone.WaitOne();
            Console.WriteLine("All Lock threads have completed.");
        }
Example #3
0
        static void Main(string[] args)
        {
            Console.WriteLine("Press enter to start");
            Console.ReadLine();

            Counter[] counters = new Counter[]
            {
                new Counter(),
                new InterlockedCounter(),
                new MutexCounter(),
            };

            int nThreads = 2;
            //int nIterations = 50000000;
            int nIterations = 500000;

            foreach (Counter counter in counters)
            {
                var elapsed = ExerciseCounter(counter, nThreads, nIterations);

                Console.WriteLine("{2} Value = {0} Expected {1} in {3} ms",
                    counter.Value,
                    nThreads * nIterations,
                    counter.GetType().Name,
                    elapsed);
            }
        }