#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <conio.h>
using namespace std;
DWORD WINAPI fun1(LPVOID lpParameter);
DWORD WINAPI fun2(LPVOID lpParameter);
int tickets=20;
CRITICAL_SECTION g_cs;
int _tmain(int argc, _TCHAR* argv[])
{
::InitializeCriticalSection(&g_cs);
HANDLE hThread1;
HANDLE hThread2;
hThread1=::CreateThread(NULL,0,fun1,NULL,0,NULL);
hThread2=::CreateThread(NULL,0,fun2,NULL,0,NULL);
::CloseHandle(hThread1);
::CloseHandle(hThread2);
::Sleep(4000);
::DeleteCriticalSection(&g_cs); //如果关键字段被删后 线程中再次申请 将出错
_getch();
return 0;
}
DWORD WINAPI fun1(LPVOID lpParameter)
{
while(1)
{
::EnterCriticalSection(&g_cs);
::Sleep(10);
if(tickets>0)
{
::Sleep(10);
cout<<" 线程1出票"<<tickets--<<endl;
::LeaveCriticalSection(&g_cs); //如果没有此句 关键段会一直被线程1掌控
}
else
{
::LeaveCriticalSection(&g_cs);
break;
}
::Sleep(1); //实验操作与教材产生不同,如果此段新增代码不用 关键事件将被线程1垄断
}
return 0;
}
DWORD WINAPI fun2(LPVOID lpParameter)
{
while(1)
{
::EnterCriticalSection(&g_cs);
::Sleep(10);
if(tickets>0)
{
::Sleep(10);
cout<<" 线程2出票"<<tickets--<<endl;
::LeaveCriticalSection(&g_cs);
}
else
{
::LeaveCriticalSection(&g_cs);
break;
}
::Sleep(1);
}
return 0;
}