码迷,mamicode.com
首页 > 其他好文 > 详细

29.4 内核模式构造

时间:2019-01-05 17:15:16      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:i++   sea   create   mil   ons   font   setevent   bsp   out   

29.4.1 Event构造

    class Program
    {
        static void Main()
        {
            int x = 0;
            const int iterations = 10000000;
            Stopwatch sw = Stopwatch.StartNew();
            
            // 1
            for (int i = 0; i < iterations; i++)
            {
                x++;
            }
            Console.WriteLine("incrementing x:{0:N0}", sw.ElapsedMilliseconds);

            // 2
            sw.Restart();
            for (int i = 0; i < iterations; i++)
            {
                M();
                x++;
                M();
            }
            Console.WriteLine("incrementing in M x:{0:N0}", sw.ElapsedMilliseconds);

            // 3
            SpinLock s1 = new SpinLock();
            sw.Restart();
            for (int i = 0; i < iterations; i++)
            {
                bool taken = false;
                s1.Enter(ref taken);
                x++;
                s1.Exit();
            }
            Console.WriteLine("incrementing in SpinLock x:{0:N0}", sw.ElapsedMilliseconds);

            // 4
            using (SimpleWaitLock sw1 = new SimpleWaitLock())
            {
                sw.Restart();
                for (int i = 0; i < iterations; i++)
                {
                    sw1.Enter();
                    x++;
                    sw1.Leave();
                }
                Console.WriteLine("incrementing x in SimpleWaitLock:{0:N0}", sw.ElapsedMilliseconds);
            }
            //incrementing x:44
            //incrementing in M x:174
            //incrementing in SpinLock x:3,186
            //incrementing x in SimpleWaitLock: 33,481

            Console.ReadKey();

            //bool createdNew;      //此代码 仅供看
            //using (new Semaphore(0, 1, "SomeUniqueStringIdentifyingMyApp", out createdNew))
            //{
            //}
        }
        [MethodImpl(MethodImplOptions.NoInlining)]
        private static void M() { }
    }
    internal sealed class SimpleWaitLock : IDisposable
    {
        private readonly AutoResetEvent m_available;
        public SimpleWaitLock()
        {
            m_available = new AutoResetEvent(true); //最开始可自由使用
        }
        public void Enter()
        {
            //在内核中阻塞,直到资源可用
            m_available.WaitOne();
        }
        public void Leave()
        {
            //让另一个线程访问资源
            m_available.Set();
        }
        public void Dispose()
        {
            m_available.Dispose();
        }
    }

 

29.4 内核模式构造

标签:i++   sea   create   mil   ons   font   setevent   bsp   out   

原文地址:https://www.cnblogs.com/kikyoqiang/p/10225194.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!