C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#多线程同步lock、Mutex

C#多线程同步lock、Mutex的实现

作者:猪猪加大码力

本文主要介绍了C#多线程同步lock、Mutex的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

C#使用多线程可以通过System.Threading命名空间下的Thread类来实现

lock和Mutex用于实现线程同步的机制:

上代码:

    class People
    {
        public People(int idd)
        {
            id = idd;
        }
        public int id;
        public int age;
    }
    class TestHelper
    {
        public TestHelper() { }
        List<People> m_data = new List<People>();

        int m_iComplete;
        private void LockThread(object obj)
        {
            List<object> parameters = (List<object>)obj;
            int idx = (int)parameters[0];
            while (true)
            {
                People data = null;
                lock(this)
                {
                    if (m_iComplete >= m_data.Count)
                    {
                        return;
                    }
                    data = m_data[m_iComplete];
                    Interlocked.Increment(ref m_iComplete);

                    data.age = data.id;
                    Console.Write("======");
                    Console.WriteLine("id:" + data.id.ToString() + ",age:" + data.age.ToString());
                }

            }
        }

        //测试lock
        public void TestLock()
        {
            DateTime time1 = DateTime.Now;
            m_iComplete = 0;
            m_data.Clear();
            for (int i = 0; i < 10000;i++)
            {
                m_data.Add(new People(i + 1));
            }
            List<Thread> threads = new List<Thread>();
            for (int i = 0; i < Environment.ProcessorCount; i++)
            {
                Thread th = new Thread(LockThread);
                th.IsBackground = true;
                List<object> objs = new List<object>();
                objs.Add(i + 1);
                th.Start(objs);
                threads.Add(th);
            }
            foreach (var th in threads)
            {
                th.Join();
            }
            DateTime time2 = DateTime.Now;
            TimeSpan deltaTime = time2.Subtract(time1);
            Console.Write("===================耗时: ");
            Console.WriteLine(deltaTime.TotalSeconds);
        }

        Mutex m_mutex = new Mutex();
        private void MutexThread(object obj)
        {
            List<object> parameters = (List<object>)obj;
            int idx = (int)parameters[0];
            while (true)
            {
                People data = null;
                //开启
                m_mutex.WaitOne();
                if (m_iComplete >= m_data.Count)
                {
                    //释放
                    m_mutex.ReleaseMutex();
                    return;
                }
                data = m_data[m_iComplete];

                Interlocked.Increment(ref m_iComplete);
                data.age = data.id;
                Console.Write("======");
                Console.WriteLine("id:" + data.id.ToString() + ",age:" + data.age.ToString());
                //释放
                m_mutex.ReleaseMutex();
            }
        }
        //测试mutex
        public void TestMutex()
        {
            DateTime time1 = DateTime.Now;
            m_iComplete = 0;
            m_data.Clear();
            for (int i = 0; i < 10000; i++)
            {
                m_data.Add(new People(i + 1));
            }
            List<Thread> threads = new List<Thread>();
            for (int i = 0;i<Environment.ProcessorCount;i++)
            {
                Thread th = new Thread(MutexThread);
                List<object> objs = new List<object>();
                objs.Add(i + 1);
                th.Start(objs);
                threads.Add(th);                
            }
            foreach(var th in threads)
            {
            	//同步等待
                th.Join();
            }
            DateTime time2 = DateTime.Now;
            TimeSpan deltaTime = time2.Subtract(time1);
            int sec = (int)deltaTime.TotalSeconds;
            Console.Write("===================耗时: ");
            Console.WriteLine(deltaTime.TotalSeconds);
        }
    }

测试:

在这里插入图片描述

起多个线程计算:

在这里插入图片描述

总结:

1、Lock是C#中的关键字,用于对代码块进行同步。Lock只能用于同一进程内的线程同步。轻量级的同步机制,开销比较小,使用简单,不能用于跨应用程序域的线程同步。
2、Mutex是系统级别的同步对象,用于跨进程的线程同步。 Mutex是内核对象,因此创建和销毁代价高,用于跨应用程序域的线程同步。

到此这篇关于C#多线程同步lock、Mutex的实现的文章就介绍到这了,更多相关C#多线程同步lock、Mutex内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文