#include <windows.h>
#include <stdio.h>
#include <iostream.h>
DWORD WINAPI Fun1Proc(
LPVOID lpParameter //thread data
);
DWORD WINAPI Fun2Proc(
LPVOID lpParameter //thread data
);
int index = 0;
int tickets = 100;
HANDLE hMutex;
void main()
{
HANDLE hThread1;
HANDLE hThread2;
//创建互斥对象
hMutex = CreateMutex(NULL,TRUE,"tickets"); //若为TRUE,则主线进程拥有互斥,FALSE则没有,这里为TRUE,已经申请里一次
//保证应用程序只有一个实例运行
if(hMutex)
{
if(ERROR_ALREADY_EXISTS == GetLastError())
{
cout<<"only one instance can run!"<<endl;
getchar();
return;
}
}
//创建线程
hThread1 = CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2 = CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
WaitForSingleObject(hMutex,INFINITE); //这里又申请里一次,此时互斥对象内部计数器为2
ReleaseMutex(hMutex); //因为申请两次,故要释放两次
ReleaseMutex(hMutex);
/* while(index++<1000)
cout<<"main thread is running"<<endl;*/
Sleep(4000);
getchar();
}
//线程1的入口
DWORD WINAPI Fun1Proc(
LPVOID lpParameter // thread data
)
{
/* while(index++<1000)
cout<<"thread1 is running"<<endl;*/
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE); //互斥对象函数,相当于一个房门,只有上一个进去的出来了,才能进去,否则就等待(一定要注意调用此函数的位置)
if(tickets>0)
{
Sleep(1);
cout<<"thread1 sell ticket : "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex); //相当于从房门内出来
//谁拥有互斥对象谁才能释放,如2拥有互斥对象,1的释放就不起效果
//若这个线程终止了,则这个互斥对象会被释放
}
return 0;
}
//线程2的入口
DWORD WINAPI Fun2Proc(
LPVOID lpParameter // thread data
)
{
/* while(index++<1000)
cout<<"thread1 is running"<<endl;*/
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread2 sell ticket:"<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}