zoukankan      html  css  js  c++  java
  • .net concurrency(parallel) data concurrency foreach

     
      static void Main(string[] args)
            {
                int[] arr= new int[1000];
                for (int i = 0; i < arr.Length; i++)
                {
                    arr[i] = i;
                }

                //sequential ForEach
                int b = 0;
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                foreach (var x in arr)
                {
                    b = b + x;
                    System.Threading.Thread.Sleep(1);
                    //Console.WriteLine(x);
                }
                stopwatch.Stop();
                Console.WriteLine("Sequential loop time in milliseconds: {0} ,value of b:{1}", stopwatch.ElapsedMilliseconds,b);

                //currency ForEach
                b = 0;
                stopwatch.Reset();
                stopwatch.Start();
                Console.WriteLine("-------------------");
                    Parallel.ForEach(arr,
                            (x) =>
                            {
                                //lock
                                /*
                                var t = "";
                                lock(t){
                                    b = b + x;
                                }
                                
    */
                                Interlocked.Add(ref b,x);
                                System.Threading.Thread.Sleep(1);
                                //Console.WriteLine(x);
                            }
                        );
                    stopwatch.Stop();
                    Console.WriteLine("Concurrency loop time in milliseconds: {0} ,value of b:{1}", stopwatch.ElapsedMilliseconds,b);
                Console.Read();

            } 

    http://msdn.microsoft.com/en-us/library/dd460717.aspx 

    http://msdn.microsoft.com/en-us/library/ff963552.aspx 
  • 相关阅读:
    算法-动态规划 Dynamic Programming--从菜鸟到老鸟
    DTW动态时间规整
    安装splash
    安装 Tesserocr (填坑)
    pip3 install tesserocr安装失败(已解决)
    从头到尾彻底理解傅里叶变换算法
    ruby之——安装gem提示:Please update your PATH to include build tools or download the DevKit
    关于0x80000000为什么等于-2147483648和负数在内存上储存的问题
    html5 canvas
    html5 视频和音频
  • 原文地址:https://www.cnblogs.com/zyip/p/2631550.html
Copyright © 2011-2022 走看看