这是我写的程序,已经比较仔细得考虑了你的问题,不过不敢保证正确,特别是在顾客取得分配给他的号码的地方,操作系统牵涉到信号量、互斥量的题目都很难说,可能很长时间都测试不出问题。你可以测试一下。有问题可以一起讨论。
程序编译连接之后就可运行了。注意连接时需要指定使用多线程静态 LIBCMT.LIB或多线程动态库MSVCRT.LIB。
#include "stdio.h"
#include "windows.h"
#define SERVER 5 /* the number of SERVERs*/
#define CUSTOMER 200 /* the number of customer wanted to be served */
#define SERVE_TIME 1000 /* the maximal time */
#define MAX_INTERVAL 200 /* the maximal interval for a customer coming*/
int number = 0; /*initialize the number of customer is zero*/
HANDLE servers,customers; /*the semaphore of servers and waiting customers*/
HANDLE mutex;
HANDLE c[CUSTOMER],b[SERVER];
DWORD WINAPI server(PVOID pvParam)
{
while(TRUE)
{
printf("a server is waiting for customer.\n");
WaitForSingleObject(customers,INFINITE); //if there is no customer waiting, the server will go to sleep;
WaitForSingleObject(mutex,INFINITE); /* get the right to change the number of waiting_customers */
number++;
int temp=number;
ReleaseSemaphore(servers,1,NULL);
ReleaseMutex(mutex);
printf("a server is serving customer %d.\n",temp);
Sleep(SERVE_TIME);
printf("a server has finished serve customer %d.\n",temp);
}
return 0;
}
DWORD WINAPI customer(PVOID pvParam)
{
printf("A customer came.\n");
ReleaseSemaphore(customers,1,NULL);
WaitForSingleObject(servers,INFINITE);
int temp= number;
printf("Customer %d is being served.\n",temp);
return 0;
}
int main(int argc, char* argv[])
{
servers = CreateSemaphore(NULL, 0, SERVER, NULL);
customers = CreateSemaphore(NULL, 0, CUSTOMER, NULL);
mutex = CreateMutex(NULL,FALSE,NULL);
int n;
int i;
for(i=0; i<SERVER; i++)
b[i]=CreateThread(NULL,0,server,NULL,0,NULL);
for(i=0; i<CUSTOMER; i++)
{
c[i]=CreateThread(NULL,0,customer,NULL,0,NULL);
n=rand()%MAX_INTERVAL;
Sleep(n);
}
WaitForMultipleObjects(CUSTOMER,c,TRUE,INFINITE);
WaitForMultipleObjects(SERVER,b,TRUE,INFINITE);
return 0;
}
温馨提示:答案为网友推荐,仅供参考