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