这个系统里面有四个角色,1 位收银员 (Cashier)、10 位顾客 (Customers)、10 - 40 位员工 (Clerks) 和 1 位经理 (Manager),如下图所示:
int main() {
int totalCones;
InitThreadPackage();
SetupSemaphores();
for (int i = 0; i < 10; i++) {
int numCones = RandomInteger(1, 4);
// Clerk Thread 由 Customer Thread 来 spawn
ThreadNew("", Customer, 1, numCones);
totalCones += numCones;
}
ThreadNew("", Cashier, 0);
ThreadNew("", Manager, 1, totalCones);
RunAllThreads();
FreeSemaphores();
return 0;
}
struct inspection {
bool passed; // init to false
Semaphore requested; // init to 0
Semaphore finished; // init to 0
Semaphore lock; // init to 1 , get the access to manager's office
}
void Manager(int totalConesNeeded) {
int numApproved = 0;
int numInspected = 0;
while (numApproved < totalConesNeeded) {
SemaphoreWait(inspection.requested);
numInspected++;
inspection.passed = RandomChoice(0, 1);
if (inspection.passed) {
numApproved++;
}
SemaphoreSignal(inspection.finished);
}
}
void Clerk(Semaphore semaToSignal) {
bool passed = false;
while(!passed) {
MakeCone();
SemaphoreWait(inspection.lock);
SemaphoreSignal(inspection.requested);
SemaphoreWait(inspection.finished);
passed = inspection.passed;
SemaphoreSignal(inspection.lock);
SemaphoreSignal(semaToSignal);
}
}
void Customer (int numCones) {
Browse();
Semaphore clerksDone; // init to 0
for (int i = 0; i < numCones; i++) {
ThreadNew("...", Clerk, 1, clerksDone);
}
for (int i = 0; i < numCones; i++) {
SemaphoreWait(clerksDone);
}
SemaphoreFree(clerksDone);
WalkToCashier();
SemaphoreWait(line.lock);
int place = line.number++;
SemaphoreSignal(line.lock);
SemaphoreSignal(line.requested);
SemaphoreWait(line.customers[place]);
}
struct line {
int number; // init to 0
Semaphore requested; // init to 0
Semaphore customers[10]; // init to [0, ..., 0]
Semaphore lock; // init to 1
}
void Cashier () {
for (int i = 0; i < 10; i++) {
SemaphoreWait(line.requested);
checkout(i);
SemaphoreSignal(line.customers[i]);
}
}