首页 > 其他分享 >89ParallarLock

89ParallarLock

时间:2023-02-10 22:11:06浏览次数:30  
标签:Console int sample 89ParallarLock WriteLine new total

        static void Main(string[] args)
        {
            int[] nums = new int[] { 1, 2, 3, 4 };
            int total = 0;
            Parallel.For<int>(0, nums.Length, () =>
            {
                return 1;
            }, (i, loopState, subtotal) =>
             {
                 subtotal += nums[i];
                 return subtotal;
             },
             (x) => Interlocked.Add(ref total, x)
             );
            Console.WriteLine("total={0}", total);

            Console.WriteLine();

            SampleClass sample = new SampleClass();
            Object obj = new object();
            Parallel.For(0, 10000000, (i) =>
            {
                lock (obj)
                {
                    sample.SimpleAdd();
                }
            });
            Console.WriteLine(sample.SomeCount);

            Console.ReadKey();
        }

        class SampleClass
        {
            public long SomeCount { get; private set; }

            public void SimpleAdd()
            {
                SomeCount++;
            }
        }

在Parallel中加锁要非常注意,长时间锁定某个共享资源所带来的同步性能损耗。

标签:Console,int,sample,89ParallarLock,WriteLine,new,total
From: https://www.cnblogs.com/wen-chen/p/17110401.html

相关文章