方法一:利用互斥对象
int tickets=100;
HANDLE hMutex;
DWORD WINAPI Fun1Proc(
LPVOID lpParameter //thread data
)
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE); //请求互斥对象
if(tickets>0)
{
Sleep(1);
cout<<"thread1 sell ticket:"<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex); //释放互斥对象
}
return 0;
}
DWORD WINAPI Fun2Proc(
LPVOID lpParameter //thread data
)
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread2 sell ticket:"<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
void main()
{
HANDLE hThread1,hThread2;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL); //创建线程
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
hMutex=CreateMutex(NULL,FALSE,NULL); //创建互斥对象
/*hMutex=CreateMutex(NULL,TRUE,NULL); //注释部分与上面一句等效
ReleaseMutex(hMutex);*/
Sleep(1000);
}
方法二:利用事件对象
#include <windows.h>
#include <iostream.h>
int tickets=100;
HANDLE g_hEvent;
DWORD WINAPI Fun1Proc(
LPVOID lpParameter //thread data
)
{
while(TRUE)
{
WaitForSingleObject(g_hEvent,INFINITE); //请求事件对象并自动置为非信号状态
if(tickets>0)
{
Sleep(1);
cout<<"thread1 sell ticket:"<<tickets--<<endl;
}
else
break;
SetEvent(g_hEvent); //设置事件对象为有信号状态
}
return 0;
}
DWORD WINAPI Fun2Proc(
LPVOID lpParameter //thread data
)
{
while(TRUE)
{
WaitForSingleObject(g_hEvent,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread2 sell ticket:"<<tickets--<<endl;
}
else
break;
SetEvent(g_hEvent);
}
return 0;
}
void main()
{
HANDLE hThread1,hThread2;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL); //创建线程
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
g_hEvent=CreateEvent(NULL,FALSE,FALSE,NULL); //创建事件对象:自动重置且初始为非信号状态
SetEvent(g_hEvent); //设置事件对象为有信号状态
//g_hEvent=CreateEvent(NULL,FALSE,TRUE,NULL); //与上面两句完成相同的功能
Sleep(4000);
CloseHandle(g_hEvent);
}
方法三:利用临界区对象
#include <windows.h>
#include <iostream.h>
int tickets=100;
CRITICAL_SECTION g_cs;
DWORD WINAPI Fun1Proc(
LPVOID lpParameter //thread data
)
{
while(TRUE)
{
EnterCriticalSection(&g_cs); //等待临界区对象的所有权限
if(tickets>0)
{
Sleep(1);
cout<<"thread1 sell ticket:"<<tickets--<<endl;
}
else
break;
LeaveCriticalSection(&g_cs); //释放临界区对象的所有权
}
return 0;
}
DWORD WINAPI Fun2Proc(
LPVOID lpParameter //thread data
)
{
while(TRUE)
{
EnterCriticalSection(&g_cs);
if(tickets>0)
{
Sleep(1);
cout<<"thread2 sell ticket:"<<tickets--<<endl;
}
else
break;
LeaveCriticalSection(&g_cs);
}
return 0;
}
void main()
{
HANDLE hThread1,hThread2;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL); //创建线程
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
InitializeCriticalSection(&g_cs); //初始化临界区对象
Sleep(4000);
DeleteCriticalSection(&g_cs); //释放临界区对象使用的所有资源
}