该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
#include
#include
#include
#include "Semaphore.h"
#define NSTUDENTS 30
#define MAX_SERVINGS 100
// This shared variable gives the number of servings currently in the barrel
int servings;
//Initialization of semaphores and shared data
Semaphore beer_empty,beer_fill,mutex;
// Define here your semaphores and any other shared data
//Called by a student process. Do not modify this.
void drink_and_think() {
// Sleep time in milliseconds
int st = rand() % 1000;
Sleep(st);
}
// Called by a student process. Do not modify this.
void get_serving(int id)
{
if (servings > 0)
servings -= 1;
else
servings = 0;
printf("ID %d got a serving. %d left\n", id, servings);
}
// Called by the bartender process.
void refill_barrel()
{
servings = 1 + rand() % MAX_SERVINGS;
printf("Barrel refilled up to -> %d\n", servings);
}
//-- Implement a synchronized version of the student
void* student(void* ptr) {
int id = *(int*)ptr;
printf("Started student %d\n", id);
do{
wait(beer_fill);
if(servings==0){
signal(beer_empty);
//wait(beer_fill);
}else{
get_serving(id);
//drink_and_think();
signal(beer_fill);
drink_and_think();
}
}while(1);
}
//-- Implement a synchronized version of the bartender
void* bartender(void* ptr) {
int id = *(int*)ptr;
printf("Started bartender %d\n", id);
do{
wait(beer_empty);
Sleep(1000);
refill_barrel();
Sleep(1000);
signal(beer_fill);
}while(true);
}
int main() {
int n;
int sid[NSTUDENTS];
HANDLE sthr[NSTUDENTS], cthr;
//-- Initialize semaphores and shared data here
beer_empty = create(1);
beer_fill = create(0);
//mutex = create(1);
// Create the student and bartender threads. Do not modify.
for (n = 0; n < NSTUDENTS; ++n) sid[n] = n + 1;
for (n = 0; n < NSTUDENTS; ++n) {
sthr[n] = CreateThread(NULL, (DWORD)NULL,
(LPTHREAD_START_ROUTINE)student, (void*)(&sid[n]),
(DWORD)NULL, NULL);
}
int cid = 0;
cthr = CreateThread(NULL, (DWORD)NULL,
(LPTHREAD_START_ROUTINE)bartender, (void*)(&cid),
(DWORD)NULL, NULL);
Sleep(100000);
return 0;
}
这个为什么运行了一阵子以后会不动了。。。跪求大神
Semaphore.h 文件如下
#define Semaphore HANDLE
void wait(Semaphore h) { // wait for a semaphore
WaitForSingleObject( h, MAXLONG);
}
void signal(Semaphore h) { // signal a semaphore
ReleaseSemaphore(h,1,NULL);
}
Semaphore create(int v) { // create a semaphore with value v
return CreateSemaphore(NULL,(long)v, MAXLONG, NULL);
}