多线程程序是经常需要用到的,本文介绍C#使用Monitor类、Lock和Mutex类进行多线程同步。
在多线程中,为了使数据保持一致性必须要对数据或是访问数据的函数加锁,在数据库中这是很常见的,但是在程序中由于大部分都是单线程的程序,所以没有加锁的必要,但是在多线程中,为了保持数据的同步,一定要加锁,好在Framework中已经为我们提供了三个加锁的机制,分别是Monitor类、Lock关键字和Mutex类。 其中Lock关键词用法比较简单,Monitor类和Lock的用法差不多。这两个都是锁定数据或是锁定被调用的函数。而Mutex则多用于锁定多线程间的同步调用。简单的说,Monitor和Lock多用于锁定被调用端,而Mutex则多用锁定调用端。 例如下面程序:由于这种程序都是毫秒级的,所以运行下面的程序可能在不同的机器上有不同的结果,在同一台机器上不同时刻运行也有不同的结果,我的测试环境为vs2005, windowsXp , CPU3.0 , 1 G monery。 程序中有两个线程thread1、thread2和一个TestFunc函数,TestFunc会打印出调用它的线程名和调用的时间(mm级的),两个线程分别以30mm和100mm来调用TestFunc这个函数。TestFunc执行的时间为50mm。程序如下:
using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace MonitorLockMutex { class Program { #region variable Thread thread1 = null; Thread thread2 = null; Mutex mutex = null; #endregion static void Main(string[] args) { Program p = new Program(); p.RunThread(); Console.ReadLine(); } public Program() { mutex = new Mutex(); thread1 = new Thread(new ThreadStart(thread1Func)); thread2 = new Thread(new ThreadStart(thread2Func)); } public void RunThread() { thread1.Start(); thread2.Start(); } private void thread1Func() { for (int count = 0; count < 10; count++) { TestFunc("Thread1 have run " + count.ToString() + " times"); Thread.Sleep(30); } } private void thread2Func() { for (int count = 0; count < 10; count++) { TestFunc("Thread2 have run " + count.ToString() + " times"); Thread.Sleep(100); } } private void TestFunc(string str) { Console.WriteLine("{0} {1}", str, System.DateTime.Now.Millisecond.ToString()); Thread.Sleep(50); } } }
运行结果如下:
private void TestFunc(string str) { lock (this) { Console.WriteLine("{0} {1}", str, System.DateTime.Now.Millisecond.ToString()); Thread.Sleep(50); } } 或者是用Monitor也是一样的,如下: private void TestFunc(string str) { Monitor.Enter(this); Console.WriteLine("{0} {1}", str, System.DateTime.Now.Millisecond.ToString()); Thread.Sleep(50); Monitor.Exit(this); }
private void thread1Func() { for (int count = 0; count < 10; count++) { mutex.WaitOne(); TestFunc("Thread1 have run " + count.ToString() + " times"); mutex.ReleaseMutex(); } } private void thread2Func() { for (int count = 0; count < 10; count++) { mutex.WaitOne(); TestFunc("Thread2 have run " + count.ToString() + " times"); mutex.ReleaseMutex(); } } private void TestFunc(string str) { Console.WriteLine("{0} {1}", str, System.DateTime.Now.Millisecond.ToString()); Thread.Sleep(50); }
private void thread1Func() { for (int count = 0; count < 10; count++) { lock (this) { mutex.WaitOne(); TestFunc("Thread1 have run " + count.ToString() + " times"); mutex.ReleaseMutex(); } } } private void thread2Func() { for (int count = 0; count < 10; count++) { lock (this) { mutex.WaitOne(); TestFunc("Thread2 have run " + count.ToString() + " times"); mutex.ReleaseMutex(); } } }
C#使用Monitor类、Lock和Mutex类进行多线程同步
原文:http://www.cnblogs.com/ly5201314/p/3546388.html