1 //多线程火车购票
2 #include "stdafx.h"
3 #include<stdlib.h>
4 #include<Windows.h>
5 #include<time.h>
6 #include<stdio.h>
7 #include<iostream>
8 using namespace std;
9
10 int a=100; //如果有100张火车票
11 HANDLE hMutex;
12 DWORD WINAPI Func(LPVOID lpParamter)//VIP窗口的功能
13 {
14 while(a>=0)
15 {
16 WaitForSingleObject(hMutex,INFINITE);//等待处理时间
17 printf("\rVIP窗口现在还有%d张票\n",a--);
18 Sleep(1000);
19 ReleaseMutex(hMutex);//放弃使用权
20 }
21 return 0;
22 }
23 //假使只有一个售票窗口
24 int main()
25 {
26 HANDLE hThread=CreateThread(NULL,0,Func,NULL,0,NULL);//创建线程
27 hMutex=CreateMutexA(NULL,FALSE,"1234");//创建互斥(锁)
28 while(a>=0)
29 {
30 printf("\r平民窗口还有%d张票\n",a--);
31 Sleep(1000);
32 }
33 CloseHandle(hThread);
34 system("pause");
35 return 0;
36 };