使用Mutex锁定功能 [英] Use Mutex to lock a function

查看:85
本文介绍了使用Mutex锁定功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:

打开许多包含相同功能的程序。

我从第一个程序实现该功能,其他程序也想实现该功能。 />
他们可以有序地使用这个功能,直到第一个程序的功能完成。



工具:

我找到了Mutex可以达到目的。



Meathod:

我编写了一个简单的程序来测试Mutex的功能。

打开两个相同的程序(如果它们是A和B)。

当我按下A的Button1时,它将计数5秒并显示在屏幕上。

如果我在5秒内按下B的Button1,它将开始计数,直到A完成。

结果符合我的预期!



但是!!!

有时,B程序崩溃并在窗口显示无响应。

我可以使用B直到A的柜台完成。

我找不到问题...



以下代码是我用MFC编码的主要代码。

I希望有人能给我一些建议。

非常感谢!!



Goal:
Open many programs which include same functions.
I implement the function from first program, and the other programs also want to implement the function.
They can use the function orderly till the function of first program have done.

Tool:
I found the "Mutex" can fulfil the purpose.

Meathod:
I programmed an easy program to test the function about the Mutex.
Opened two same programs(if they are A and B).
When I pressed the Button1 of A, it will count 5 seconds and show on screen.
If I pressed the Button1 of B inside the 5 seconds, it will starts to count till the A has done.
The result conformed with my anticipation!

BUT!!!
Sometimes, the B program crashed and showed "No response" on the windows.
I can use the B till the counter of A has done.
I can't find the question...

The following code is main code which I coded by MFC.
I hope someone can give me some suggestions.
Thanks a lot!!

CMutex mutex(false,_T("CodeProject"));  //declare a named mutex

void CMutextestDlg::OnBnClickedButton1()
{
     mutex.Lock(); //Lock the thread
     
     //Count for 5 seconds.
     CString str;
     for(int i=0;i<=5;i++)
     {	
          str.Format(_T("%d"),i);
	  SetDlgItemText(IDC_STATIC,str);
	  Sleep(1000);
     }
     SetDlgItemText(IDC_STATIC,_T("End")); //Counter completed

     mutex.Unlock(); //Unlock the thread
}

推荐答案

互斥锁定调用是阻塞调用。整个程序的执行被阻止,直到它可以实现锁定。对于基于对话框的应用程序,锁定事件处理程序是一个很大的禁忌。您仍然可以执行类似的操作,您无法在处理GUI更新和其他Windows消息的同一线程上执行此操作。
Mutex lock calls are blocking calls. The execution of the entire program is blocked there until it can achieve a lock. For a dialog based application, locking on an event handler is a big no-no. You can still do something similar, you just can't do it on the same thread that handles the GUI updates and other windows messages.


这篇关于使用Mutex锁定功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆