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

来自:网络
时间:2024-09-10
阅读:

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);
        }
    }

测试:

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

起多个线程计算:

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

总结:

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

返回顶部
顶部