题目:PV操作。编写源程序。顾客进店看能不能进餐,有座位进餐,没座位等待。管理员扫描座位,有位子通知就餐。
分析:使用两个信号量,restSeats表示剩余的座位,初始为5,fullSeats表示已占的座位,初始为0。
顾客线程:P(restSeats)、V(fullSeats)
服务员线程:P(fullSeats)、V(restSeats)
有关Windows下的线程操作请看:笔记:windows环境下线程编程(C++实现同步与互斥)
题解:
#include<iostream>
#include <stdio.h>
#include<string.h>
#include<windows.h>
using namespace std;
HANDLE restSeats = 0;
HANDLE fullSeats = 0;
bool g_continue = true; //控制程序运行和结束
DWORD WINAPI Server(LPVOID); //服务员线程
DWORD WINAPI Client(LPVOID);//顾客线程
int main()
{
restSeats = CreateSemaphore(NULL, 5, 5, NULL);
fullSeats = CreateSemaphore(NULL, 0, 5, NULL);
DWORD threadID[2];
HANDLE hThreads[2];
//创建服务员线程
hThreads[0] = CreateThread(NULL, 0, Server, NULL, 0, &threadID[0]);
if (hThreads == NULL) return -1;
//创建顾客线程
hThreads[1] = CreateThread(NULL, 0, Client, NULL, 0, &threadID[1]);
if (hThreads == NULL) return -1;
while (g_continue){
if (getchar()){ //按回车后终止程序运行
g_continue = false;
}
}
return 0;
}
DWORD WINAPI Server(LPVOID lpPara)
{
while (g_continue){
WaitForSingleObject(fullSeats, INFINITE);//INFINITE表示无限等待,一直等到当g_hMutex为1时才进行下面操作
//通知就餐
cout<<"服务员:通知进餐"<<endl;
Sleep(2000);
ReleaseSemaphore(restSeats, 1, NULL);
}
return 0;
}
DWORD WINAPI Client(LPVOID lpPara)
{
while (g_continue){
WaitForSingleObject(restSeats, INFINITE);//INFINITE表示无限等待,一直等到当g_hMutex为1时才进行下面操作
//就餐
cout<<"顾客:进店坐下并就餐"<<endl;
Sleep(1000);
ReleaseSemaphore(fullSeats, 1, NULL);
}
return 0;
}