分享

C#中使用Monitor类、Lock和Mutex类来同步多线程的执行

 goodwangLib 2014-05-03

#中使用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。程序如下:
[c-sharp] view plaincopy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading ;  
  6.   
  7. namespace 多线程  
  8. {  
  9.     class Program  
  10.     {  
  11.         Thread thread1 = null;  
  12.         Thread thread2 = null;   
  13.         Mutex mutex = null;  
  14.   
  15.         public static void Main()  
  16.         {  
  17.             //Monitor类的使用  
  18.             //lock语句其实后台解析为Monitor类的调用   
  19.             //Enter方法一直等待获得锁定的对象  
  20.             //Exit方法是接触锁定  
  21.             //一次只能有一个线程成为对象锁定的拥有者,只要解除了锁定,就进入了同步代码段。  
  22.             //显示使用这个类的好处理,可以用try catch,如果出现异常,也可以保证正常的解除锁定  
  23.             Program p = new Program();   
  24.             p.RunThread();  
  25.             Console.ReadLine();  
  26.         }  
  27.   
  28.         public Program()  
  29.         {   
  30.             mutex = new Mutex() ;   
  31.             thread1 = new Thread( new ThreadStart( Thread1Func ) ) ;   
  32.             thread2 = new Thread( new ThreadStart( Thread2Func ) ) ;  
  33.         }  
  34.   
  35.         public void RunThread()   
  36.         {   
  37.             thread1.Start() ;   
  38.             thread2.Start() ;   
  39.         }  
  40.   
  41.         private void Thread1Func()   
  42.         {  
  43.             for (int count = 0; count < 10; count++)  
  44.             {   
  45.                 TestFunc("线程1 运行第 " + count.ToString() + " 次") ;   
  46.                 Thread.Sleep( 30 ) ;  
  47.             }  
  48.         }          
  49.           
  50.         private void Thread2Func()   
  51.         {  
  52.             for (int count = 0; count < 10; count++)  
  53.             {  
  54.                 TestFunc("   线程2 运行第 " + count.ToString() + " 次");  
  55.                 Thread.Sleep( 100 ) ;   
  56.             }  
  57.         }         
  58.           
  59.         private void TestFunc( string str)   
  60.         {  
  61.             Console.WriteLine("{0} {1}", str,  System.DateTime.Now.Millisecond.ToString() );   
  62.             Thread.Sleep(50);   
  63.         }  
  64.     }  
  65.   
  66. }  
运行结果如下:
        可以看出如果不加锁的话,这两个线程基本上是按照各自的时间间隔+TestFunc的执行时间(50mm)对TestFunc函数进行读取。因为线程在开始时需要分配内存,所以第0次的调用不准确,从第1~9次的调用可以看出,thread1的执行间隔约是80mm,thread2的执行间隔约是150mm。
现在将TestFunc修改如下:
[c-sharp] view plaincopy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading ;  
  6.   
  7. namespace 多线程  
  8. {  
  9.     class Program  
  10.     {  
  11.         Thread thread1 = null;  
  12.         Thread thread2 = null;   
  13.         Mutex mutex = null;  
  14.   
  15.         public static void Main()  
  16.         {  
  17.             //Monitor类的使用  
  18.             //lock语句其实后台解析为Monitor类的调用   
  19.             //Enter方法一直等待获得锁定的对象  
  20.             //Exit方法是接触锁定  
  21.             //一次只能有一个线程成为对象锁定的拥有者,只要解除了锁定,就进入了同步代码段。  
  22.             //显示使用这个类的好处理,可以用try catch,如果出现异常,也可以保证正常的解除锁定  
  23.             Program p = new Program();   
  24.             p.RunThread();  
  25.             Console.ReadLine();  
  26.         }  
  27.   
  28.         public Program()  
  29.         {   
  30.             mutex = new Mutex() ;   
  31.             thread1 = new Thread( new ThreadStart( Thread1Func ) ) ;   
  32.             thread2 = new Thread( new ThreadStart( Thread2Func ) ) ;  
  33.         }  
  34.   
  35.         public void RunThread()   
  36.         {   
  37.             thread1.Start() ;   
  38.             thread2.Start() ;   
  39.         }  
  40.   
  41.         private void Thread1Func()   
  42.         {  
  43.             for (int count = 0; count < 10; count++)  
  44.             {   
  45.                 TestFunc("线程1 运行第 " + count.ToString() + " 次") ;   
  46.                 Thread.Sleep( 30 ) ;  
  47.             }  
  48.         }          
  49.           
  50.         private void Thread2Func()   
  51.         {  
  52.             for (int count = 0; count < 10; count++)  
  53.             {  
  54.                 TestFunc("   线程2 运行第 " + count.ToString() + " 次");  
  55.                 Thread.Sleep( 100 ) ;   
  56.             }  
  57.         }         
  58.           
  59.         private void TestFunc( string str)   
  60.         {  
  61.             //lock( this )  
  62.             //{  
  63.             //    Console.WriteLine("{0} {1}", str,  System.DateTime.Now.Millisecond.ToString() );   
  64.             //    Thread.Sleep( 50);   
  65.             //}  
  66.               
  67.             //Monitor类写法  
  68.             //Monitor.Enter( this ) ;  
  69.             //Console.WriteLine("{0} {1}", str, System.DateTime.Now.Millisecond.ToString());  
  70.             //Thread.Sleep( 50);  
  71.             //Monitor.Exit( this ) ;  
  72.   
  73.             //Monitor有一好处,可以传送一个超时值  
  74.             //如果线程等待了500MM还是拿不到锁定的话,就不再等了。  
  75.   
  76.             if( Monitor.TryEnter( this , 500 ) )  
  77.             {  
  78.                 Console.WriteLine("{0} {1}", str, System.DateTime.Now.Millisecond.ToString());  
  79.                 Thread.Sleep(50);  
  80.                 Monitor.Exit(this);  
  81.             }  
  82.   
  83.         }  
  84.     }  
  85.   
  86. }  
其中Enter和Exit都是Monitor中的静态方法。
运行Lock结果如下:
        让我们分析一下结果,同样从第1次开始。相同线程间的调用时间间隔为线程执行时间+TestFunc调用时间,不同线程间的调用时间间隔为TestFunc调用时间。例如:连续两次调用thread1之间的时间间隔约为30+50=80;连续两次调用thread2之间的时间间隔约为100+50=150mm。调用thread1和thread2之间的时间间隔为50mm。因为TestFunc被lock住了,所以一个thread调用TestFunc后,当其它的线程也同时调用TestFunc时,后来的线程即进被排到等待队列中等待,直到拥有访问权的线程释放这个资源为止。
        这就是锁定被调用函数的特性,即只能保证每次被一个线程调用,线程优先级高的调用的次数就多,低的就少,这就是所谓的强占式。
        下面让我们看看Mutex类的使用方法,以及与Monitor和Lock的区别。
将代码修改如下:
        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);
        }
运行结果如下:
        可以看出,Mutex只能互斥线程间的调用,但是不能互斥本线程的重复调用,即thread1中waitOne()只对thread2中的waitOne()起到互斥的作用,但是thread1并不受本wainOne()的影响,可以调用多次,只是在调用结束后调用相同次数的ReleaseMutex()就可以了。
        那么如何使线程按照调用顺序来依次执行呢?其实把lock和Mutex结合起来使用就可以了,改代码如下:
        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();
                }
            }

        }

一个monitor 的例子:

using System.Collections.Generic;
using System.Threading;

namespace OpenSim.Framework
{
    public class BlockingQueue<T>
    {
        private readonly Queue<T> m_pqueue = new Queue<T>();
        private readonly Queue<T> m_queue = new Queue<T>();
        private readonly object m_queueSync = new object();

        public void PriorityEnqueue(T value)
        {
            lock (m_queueSync)
            {
                m_pqueue.Enqueue(value);
                Monitor.Pulse(m_queueSync);
            }
        }

        public void Enqueue(T value)
        {
            lock (m_queueSync)
            {
                m_queue.Enqueue(value);
                Monitor.Pulse(m_queueSync);
            }
        }

        public T Dequeue()
        {
            lock (m_queueSync)
            {
                if (m_queue.Count < 1 && m_pqueue.Count < 1)
                {
                    Monitor.Wait(m_queueSync);
                }

                if (m_pqueue.Count > 0)
                    return m_pqueue.Dequeue();
                return m_queue.Dequeue();
            }
        }

        public T Dequeue(int msTimeout)
        {
            lock (m_queueSync)
            {
                if (m_queue.Count < 1 && m_pqueue.Count < 1)
                {
                    Monitor.Wait(m_queueSync, msTimeout);
                }

                if (m_pqueue.Count > 0)
                    return m_pqueue.Dequeue();
                if (m_queue.Count > 0)
                    return m_queue.Dequeue();
                return default(T);
            }
        }

        public bool Contains(T item)
        {
            lock (m_queueSync)
            {
                if (m_pqueue.Contains(item))
                    return true;
                return m_queue.Contains(item);
            }
        }

        public int Count()
        {
            lock (m_queueSync)
            {
                return m_queue.Count+m_pqueue.Count;
            }
        }

        public T[] GetQueueArray()
        {
            lock (m_queueSync)
            {
                return m_queue.ToArray();
            }
        }
    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多