How expensive is the lock statement?

后端 未结 7 858
面向向阳花
面向向阳花 2020-11-28 07:00

I\'ve been experimenting with multi threading and parallel processing and I needed a counter to do some basic counting and statistic analysis of the speed of the processing.

7条回答
  •  借酒劲吻你
    2020-11-28 07:17

    The cost for a lock in a tight loop, compared to an alternative with no lock, is huge. You can afford to loop many times and still be more efficient than a lock. That is why lock free queues are so efficient.

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace LockPerformanceConsoleApplication
    {
        class Program
        {
            static void Main(string[] args)
            {
                var stopwatch = new Stopwatch();
                const int LoopCount = (int) (100 * 1e6);
                int counter = 0;
    
                for (int repetition = 0; repetition < 5; repetition++)
                {
                    stopwatch.Reset();
                    stopwatch.Start();
                    for (int i = 0; i < LoopCount; i++)
                        lock (stopwatch)
                            counter = i;
                    stopwatch.Stop();
                    Console.WriteLine("With lock: {0}", stopwatch.ElapsedMilliseconds);
    
                    stopwatch.Reset();
                    stopwatch.Start();
                    for (int i = 0; i < LoopCount; i++)
                        counter = i;
                    stopwatch.Stop();
                    Console.WriteLine("Without lock: {0}", stopwatch.ElapsedMilliseconds);
                }
    
                Console.ReadKey();
            }
        }
    }
    

    Output:

    With lock: 2013
    Without lock: 211
    With lock: 2002
    Without lock: 210
    With lock: 1989
    Without lock: 210
    With lock: 1987
    Without lock: 207
    With lock: 1988
    Without lock: 208
    

提交回复
热议问题