多线程程序是常常须要用到的,本文介绍C#使用Monitor类、Lock和Mutex类进行多线程同步。数据库
在多线程中,为了使数据保持一致性必需要对数据或是访问数据的函数加锁,在数据库中这是很常见的,可是在程序中因为大部分都是单线程的程序,因此没有加锁的必要,可是在多线程中,为了保持数据的同步,必定要加锁,好在Framework中已经为咱们提供了三个加锁的机制,分别是Monitor类、Lock关键字和Mutex类。 其中Lock关键词用法比较简单,Monitor类和Lock的用法差很少。这两个都是锁定数据或是锁定被调用的函数。而Mutex则多用于锁定多线程间的同步调用。简单的说,Monitor和Lock多用于锁定被调用端,而Mutex则多用锁定调用端。 例以下面程序:因为这种程序都是毫秒级的,因此运行下面的程序可能在不一样的机器上有不一样的结果,在同一台机器上不一样时刻运行也有不一样的结果,个人测试环境为vs2005, windowsXp , CPU3.0 , 1 G monery。 程序中有两个线程thread一、thread2和一个TestFunc函数,TestFunc会打印出调用它的线程名和调用的时间(mm级的),两个线程分别以30mm和100mm来调用TestFunc这个函数。TestFunc执行的时间为50mm。程序以下:windows
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(); } } }