线程间同步之 Mutex(mutual exclusion 互斥量)

Mutex是提供同步访问多个进程的一个类。和Monitor极其类似。
相同点:Mutex和Monitor都只能有一个线程拥有锁定。
区别:Mutex可用于进程内的线程同步,也可用于进程同步,一般用于进程同步。Monitor则只能用于进程内的线程同步。当进行进程内的线程同步时,优先选择Monitor。因为Monitor应用在用户模式下的线程同步技术,而Mutex是应用于内核级别的线程同步技术,线程的执行是在用户模式下执行的,而要切换到内核模式大概要消耗1000个CPU时钟,所以进行进程内的线程同步时优先选择Monitor,而进行进程间的同步时,Mutex是不二之选。

当声明Mutex时必须指定名称,否则只能进行进程内的线程同步。

如下所示:

1 bool blCreate;
2 Mutex mutex=new Mutex(false,"MutexName",blCreate)

在同一个线程内mutex.WaitOne()和mutex.ReleaseMutex()必须成对出现。

下边举两个例子说明Mutex的应用

1、只能有一个程序实例在运行。

 1         /// <summary>
2 /// 应用程序的主入口点。
3 /// </summary>
4 [STAThread]
5 static void Main()
6 {
7 bool ret;
8 System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out ret);
9 if (ret)
10 {
11 Application.EnableVisualStyles();
12 Application.SetCompatibleTextRenderingDefault(false);
13 System.Windows.Forms.Application.DoEvents();
14 Application.Run(new Form1());
15 mutex.ReleaseMutex();
16 }
17 }

程序执行的时候,只能允许有一个实例在执行,用是否是本程序创建的互斥量来判断,本程序是ret。

2、多个进程间用Mutex同步的例子。

创建一个Windows窗体应用程序,添加一个Button按钮,Form1窗体代码如下:

 1         public Form1()
2 {
3 InitializeComponent();
4 }
5
6 System.Threading.Mutex mutex = new System.Threading.Mutex(false, Application.ProductName);
7 private void button1_Click(object sender, EventArgs e)
8 {
9 Thread thd = new Thread(new ParameterizedThreadStart(MutexThread));
10 thd.Start();
11
12 }
13 private void MutexThread( object obj)
14 {
15 try
16 {
17 mutex.WaitOne();
18 MessageBox.Show("Get Mutex");
19 Thread.Sleep(10000);
20 }
21 catch (Exception ex)
22 {
23 MessageBox.Show(ex.Message);
24 }
25 finally
26 {
27 mutex.ReleaseMutex();
28 }
29 }

生成完成后同时运行两个实例。

单击第一个实例的Button,再单击第二个实例的Button。可见实例一马上会弹出消息“Get Mutex”, 而实例二则等待10秒钟后才弹出来。

这是因为实例一开启了一个线程,这个线程锁定了名称为Application.ProductName的系统级的互斥量。而实例二只能等待实例一中的线程将互斥量释放掉以后,才能获得锁定。所以这才是实例二需要等待10秒钟的真正原因。

posted on 2011-10-21 00:15  李国清  阅读(6351)  评论(2编辑  收藏  举报

导航