当前位置: 代码网 > it编程>编程语言>C# > C#多线程同步lock、Mutex的实现

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

2024年06月14日 C# 我要评论
c#使用多线程可以通过system.threading命名空间下的thread类来实现lock和mutex用于实现线程同步的机制:上代码: class people { pu

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内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com