21
2017
09

编程范式 18 冰淇淋商店

clerks
40 cones
10 customers 每人吃1-4个冰淇淋 FIFO
manager不同意要重做 同时只能有一个clerk和manager见面
cashier
需要四类线程

  1. manager
  2. clerks
  3. customers
  4. cashier
int main()
{
    int totalCones=0;
    InitThreadPackage();
    SetupSemaphores();
    for(int i=0;i<10;i++)
    {
        int numCones=RandomInteger(1,1);
        ThreadNew(,Customer,1,numCunstomers);
        totalCones+=numCones;
    }
    ThreadNew(,Cashier,0);
    ThreadNew(,Manager,1,totalCones);
    RunAllThreads();
    FreeSemaphores();
    return 0;
} 
struct inspection{
    bool passed;//false
    Semaphore requested;//0
    Semaphore finished;//0
    Semphore lock;//1
}
void Manager(int totalConesNeeded)
{
    int numApproved=0;
    int numInsected=0;
    while(numApproved<totalConesNeeded)
    {
        sw(inspection<requested);
        numINspected++;
        inspection.passed=Random(1,0)
        //50%概率通过
        if(inspection.passed)
        {
            numApproved++;
        }
        ss(inspected.finished);
    }
}
void clerk(Semaphore semaToSignal)
{
    bool passed=false;
    while(!passed)
    {
        MakeCone();
        sw(inspection.lock);//semaphore wait
        ss(inspection.requested);//semaphore signal
        sw(inspection.finished);
        passed=inspection.passed;
        ss(inspection.lock);
    }
    ss(semaToSignal);
}
void Customer(int numCones)
{
    Brow X();//等店员做完
    Samphore clerkDone;
    for(int i=0;i<numCones;i++)
    {
        TN(,1,clerkDone);//ThreadNew
    }
    for(int i=0;i<numCones;i++)
    {
        sw(clerksDone);
    }
    SemaphoreFree(clerksDone);
    WalkToCashier();
    ss(line.requested);
    sw(line.lock);
    int place=line.number++;
    ss(line.lock);
    ss(line.requested);
    sw(line.customers[place]);
}   
struct line{
    int number;//0
    Semaphore requested;//0
    Semaphore Customers[10];
    Semaphore lock;//1
}
void Cashier()
{
    for(int i=0;i<10;i++)
    {
        sw(line.requested);
        checkout(i);
        semaphore line(customers[i]);
    }
}
上一篇:【转】【DBSDFZOJ 1163】分治 第K小元素(分治) 下一篇:java中创建线程的两种方式