#include<cstdarg>
#include<Windows.h>
#include<iostream>
#include <cmath>
#include<ctime>
#define MAX_COUNT 10//最多理發人數
#define CHAIRS 4//店中椅子的總數目
using namespace std;
intwaiting=0; //等待理發的顧客人數
char close_door; //關門
int count=0; //顧客的序号
int finish=0; //已經理完發的顧客人數
HANDLE Mutex =CreateMutex(NULL, FALSE, "Mutex"); //用來實作程序的互斥
HANDLE barbers =CreateSemaphore(NULL, 1,1, "barbers"); //定義信号量來進行線程間的同步
HANDLE customers =CreateSemaphore(NULL,0,CHAIRS,"customers"); //定義信号量來進行線程間的同步
int random()//定義随機函數來産生顧客,并使兩個顧客間的時間少于10秒
{
srand((int)time(NULL));
return rand()%5000;
}
DWORD WINAPI customer(LPVOID pParm2)// 顧客線程
if(ReleaseSemaphore(customers,1,NULL))//V(customer)
WaitForSingleObject(Mutex ,INFINITE);
count++;
cout<<"您是第 "<<count<<" 位顧客,歡迎您的到來^_^ "<<endl;
if (waiting!=0)
cout<<"現在有"<<waiting <<" 位顧客在等待理發,請您耐心等待^_^"<<endl;
else
cout<<"沒有顧客在理發,我馬上為您服務^_^"<<endl;//輸出有多少人在等待
waiting++;
ResumeThread(customers);//喚醒理發師程序
ReleaseMutex(Mutex);//釋放互斥量,以便其他線程使用
WaitForSingleObject(barbers,INFINITE); //等待理發
cout<<"對不起,沒有空椅子……第"<<count<<"個顧客離開理發店"<<endl; //沒有椅子,顧客直接離開
return 0;
DWORD WINAPI barber(LPVOID pParm1)//理發師線程
while(true)//外循環
WaitForSingleObject(customers,INFINITE);//p(customers),等待顧客
WaitForSingleObject(Mutex,INFINITE); //等待互斥量
ReleaseSemaphore(barbers,1,NULL); //釋放信号量
ResumeThread(barbers); //喚醒顧客程序
Sleep(5000); //模拟理發
finish++; //理發完畢的顧客數目加1
cout<<"第"<<finish<<"個顧客理發完畢,離開 "<<endl;
waiting--; //等待的人數減1
ReleaseMutex(Mutex); //v(mutex);
int main( )//實作線程的操作
cout<<"***************新店開張,熱烈歡迎光大顧客的光臨!!***********"<<endl;
cout<<"本店中共有"<<CHAIRS<<"把椅子"<<endl;
HANDLE hThreadCustomer;
HANDLE hThreadBarder;
hThreadBarder=CreateThread(NULL,0,barber,NULL,0,NULL); //産生一個理發師程序
while(close_door!='y')
{
Sleep(random());//rand()函數實作顧客随機到來
//cout<<endl<<"正在營業,請進!"<<endl;
if (finish>=MAX_COUNT)//如果完成數超過8并且沒有人等待
while(waiting!=0)
Sleep(1000);
continue;
cout<<"已經為"<<finish<<"個顧客理發了,是否停止營業?"<<endl; //提示是否關門
cin>>close_door;
if (close_door=='y')
cout<<"暫停營業!歡迎下次光臨!"<<endl;
system("pause");
else
finish=0;
count=0;
cout<<"繼續營業"<<endl;
hThreadCustomer=CreateThread(NULL,0,customer,NULL,0,NULL);
本文轉自 chenming421 51CTO部落格,原文連結:http://blog.51cto.com/wnqcmq/1093356