Blog Archive

Tuesday, July 31, 2012

Parallel.For vs. Synchronization using ManualResetEvent

For 100 threads Synchronization using primitives seems a bit fater, 14s vs. 17s
(but for some reason WCF does not go parallel even after adjusted throtlelling=100
machine.config processModel min/max work/Id thread =100/200)
    class Program
    {
        private const int NUM = 100;
        static CountdownEvent cde = new CountdownEvent(NUM);
        static ManualResetEvent mre = new ManualResetEvent(false);
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            PFor();
          //  SyncWithPrimitives();
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
            Console.ReadKey();
        }

        private static void PFor()
        {
            c.Open();
            Parallel.For(0, NUM, new ParallelOptions() {MaxDegreeOfParallelism=NUM}, (i) =>
            {
                c.GetData(1111);
              //  Console.WriteLine(c.GetData(1111));
            });
            c.Close();
        }

        #region Using Threading Primitives

        private static void SyncWithPrimitives()
        {
            Thread[] threads = new Thread[NUM];
            for (int i = 0; i < NUM; i++)
            {
                threads[i] = new Thread(SetThread);
                threads[i].Start();
            }
            cde.Wait();
            c.Open();
            mre.Set();  // all threads burst into calling WCF

            cde = new CountdownEvent(NUM);  // count down to all finish calls to WCF
            cde.Wait();
            c.Close();
        }

        static ServiceReference1.Service1Client c = new ServiceReference1.Service1Client();
        static void SetThread()
        {
            cde.Signal();
            mre.WaitOne();
            c.GetData(1111);
          // Console.WriteLine( c.GetData(1111));
            cde.Signal();  // call finished
        }

        #endregion

    }

WCF:

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            Random r = new Random();
            Thread.Sleep(TimeSpan.FromSeconds(1));
            return r.NextDouble().ToString();
        }

No comments: