互斥对象:
1:谁拥有谁释放,其他人释放无效
2:多次拥有多次释放,要不然无法释放完权限
3:当某个线程拥有对象,如果该线程执行完后即使没有释放互斥对象,
操作系统也会把互斥对象释放掉,让别的线程有可能申请到该互斥对象
4.如何辨别申请到的互斥对象是上一个线程执行出现问题时释放的还是线程没有调用releaseMutex时释放的,或者是正常申请到的即是上一个线程
正常释放的,我们可以根据WaiteForSingObject的返回值来判断。当互斥对象是在前两者情况的到时,这时要注意互斥对象
5.命名互斥:可用来判断是否有意实例在运行。比如金山词霸不能在一台机器上运行两个
#include<windows.h>
#include <iostream.h>
int tickets=100;
HANDLE hMutex;
DWORD WINAPI Fun1Proc(LPVOID IpParameter)//thread data
{
while(true)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
cout<<"Thread1 is selling the :"<<tickets--<<endl;
Sleep(5);
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI Fun2Proc(LPVOID IpParameter)//thread data
{
while(true)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
cout<<"Thread2 is selling the :"<<tickets--<<endl;
Sleep(5);
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
void main()
{
HANDLE hThread1,hThread2;
/*hMutex=CreateMutex(NULL,false,NULL);//匿名互斥对象
*/
hMutex=CreateMutex(NULL,true,"tickets");
if(hMutex)//判断是否已经有一个事例在运行
{
if(ERROR_ALREADY_EXISTS==GetLastError())
{
cout<<"only instance can run!"<<endl;
return;
}
}
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);//关闭句柄,但并不是关闭新建的线程
CloseHandle(hThread2);
cout<<"main thread is running "<<endl;
Sleep(100);//为了使线程1尽可能的运行
}