64,282
社区成员
发帖
与我相关
我的任务
分享
#ifndef SELL_TICKETS_H
#define SELL_TICKETS_H
#include "afxmt.h"
class SellTickets //卖票类
{
public:
SellTickets(int n);
~SellTickets();
void ShowWindowNum(); //输出窗口号
void ShowTicketsCount(); //输出车票数量
void SellOneTicket(); //卖一张票
private:
CMutex m_mutex;
int num; //窗口号码
int count; //车票数量
};
#endif
#include "SellTickets.h"
#include "stdafx.h"
#include "iostream"
using namespace std;
SellTickets::SellTickets(int n)
{
SellTickets::count = 100; //车票总数
SellTickets::num = n; //窗口号
SellTickets::m_mutex.Lock();//上锁
}
SellTickets::~SellTickets()
{
SellTickets::m_mutex.Unlock();//解锁
}
void SellTickets::ShowWindowNum()
{
cout<<"这是"<<num<<"号窗口"<<endl;
}
void SellTickets::ShowTicketsCount()
{
cout<<"车票总数:"<<count<<endl;
}
void SellTickets::SellOneTicket()
{
if(count>0)
SellTickets::count--;//车票数量减一
else
{
cout<<"车票已经卖完了"<<endl;
cin.get();
cin.get();
}
}
#include "SellTickets.h"
#include "stdafx.h"
#include "iostream"
using namespace std;
DWORD WINAPI ThreadProc1(LPVOID lpParameter)
{
cout<<"窗口1卖票"<<endl;
SellTickets t1(1); //循环调用,一直卖票直到卖完
while(1)
{
t1.ShowTicketsCount();
t1.SellOneTicket();
Sleep(500);
}
return 0;
}
DWORD WINAPI ThreadProc2(LPVOID lpParameter)
{
cout<<"窗口2卖票"<<endl;
SellTickets t2(2);
while(1)
{
t2.ShowTicketsCount();
t2.SellOneTicket();
Sleep(500);
}
return 0;
}
void main()
{
//模拟两个窗口同时卖票
HANDLE hThread1 = CreateThread(NULL,NULL,ThreadProc1,NULL,NULL,NULL);
HANDLE hThread2 = CreateThread(NULL,NULL,ThreadProc2,NULL,NULL,NULL);
}
#include "SellTickets.h"
#include "stdafx.h"
#include "iostream"
变成#include "stdafx.h"
#include "iostream"
#include "SellTickets.h"
后,