睡眠理发师问题代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define CHAIRS 3
#define BARBERS 1
typedef HANDLE semaphore;
static int count=0; //count the total number of coustomers entered the shop
int leaved=0; //record the total number of coustomers leaved without been served
int waiting=0;
time_t endtime; //关闭营业的时间
semaphore customers=CreateSemaphore(NULL,0,CHAIRS,TEXT("customers")); //coustomers初始化为0,最大顾客数为10
semaphore barbers=CreateSemaphore(NULL,BARBERS,BARBERS,TEXT("barbers")); //barbers的数量初始化为3,假设一共有3个barber
HANDLE mutex=CreateMutex(NULL,FALSE,TEXT("mutex")); //建立互斥变量,用于保护共享资源
DWORD WINAPI barber(LPVOID lparameter);
DWORD WINAPI customer(LPVOID lparameter);
void cut_hair();
void get_cuthair();
void wait();
void leave();
void enter();
void up(HANDLE hHandle){ //UP operation
ReleaseSemaphore(hHandle,1,NULL);
ResumeThread(hHandle);
}
void upMutex(HANDLE hMutex){ //UP Mutex
ReleaseMutex(hMutex);
}
void down(HANDLE hHandle){ //DOWN operation
WaitForSingleObject(hHandle,INFINITE);
}
int main(){
endtime=time(0)+20000;
HANDLE barberThread=CreateThread(NULL,0,barber,NULL,0,NULL); //start the barberThread
HANDLE customerThread;
while(count<20){
customerThread=CreateThread(NULL,0,customer,NULL,0,NULL); //start the coustomerThread
srand(unsigned(time(0)));
int time=rand()%1000+50;
//int time=50;
Sleep(time);
}
// Sleep(200000);
CloseHandle(barberThread);
CloseHandle(customerThread);
CloseHandle(barbers);
CloseHandle(customers);
CloseHandle(mutex);
return 0;}
DWORD WINAPI barber(LPVOID lparameter){
while(time(0)
down(mutex); //aquire access to waiting
//cout<<"等待的顾客数::"<
waiting=waiting-1; //decrement count of waiting
upMutex(mutex);
cut_hair(); //outside the critical rigon
up(barbers); //one barber is now ready
}
return 0;
}
DWORD WINAPI customer(LPVOID lparameter){
// while(time(0)
down(mutex);
cout<<"等待的顾客数: "<
if(waiting
waiting=waiting+1; //increment the waiting coustomers
up(customers); //wake up barber if neccessary
upMutex(mutex);
//release access to waiting
down(barbers); //blocked if barber is 0
get_cuthair();
}
else{
upMutex(mutex);
leave(); }
// }
return 0;
}
void cut_hair(){
static int served=0;
served++;
//int t=count;
cout<<"理发师帮第 "<
cout<<"第 "<
}
void get_cuthair(){
//cout<<"有理发师,第"<
Sleep(1050);
//cout<<"第"<
void enter(){
count++;
SYSTEMTIME sys;
GetLocalTime( &sys );
cout<
sys.wMonth, sys.wDay, sys.wHour, sys.wMinute, sys.wSecond,sys.wDayOfWeek);
}
void wait(){
cout<<"有空位,第 "<
void leave(){
cout<<"没有空椅子,第"<