zoukankan      html  css  js  c++  java
  • barber question

    理发师问题:
    一个理发店由一个有几张椅子的等待室和一个放有一张理发椅的理发室组成。
    1. 若没有要理发的顾客,则理发师去睡觉;
    2. 若一顾客进入理发店,理发师正在为别人理发,且等待室有空椅子,则该顾客就找张椅子按顺序坐下;
    3. 若一顾客进入理发店,理发师在睡觉,则叫醒理发师为该顾客理发;
    4. 若一顾客进入理发店且所有椅子都被占用了,则该顾客就离开。

    互斥信号量:mutex 用来互斥对临界变量waiting的访问

    计数信号量 customers用来记录等候的顾客数据,二进制信号量barber用来表示理发师是否可用;

    临界变量:waiting由理发师进程和顾客进程共同访问,用来记录在椅子上等着的顾客数

                  N 为椅子数,为最多等候的顾客数

    #define CHAIRS 5 
    typedef int semaphore ;

    semaphore mutex = 1 ;
    semaphore customers = 0 , barber = 0 ;
    int waiting = 0 ;

    void Customer() {
    while (true) {
    // Is there any empty seat
    wait(mutex) ;
    if (waiting < CHAIRS) {
    /*
    Some empty seats => seat down
    */
    waiting ++ ;
    // if the barber is sleeping, wakes up him
    signal(customers) ;
    signal(mutex) ;
    /*
    Is the barber working
    yes => waiting
    */
    wait(barber) ;
    // no => get hair cutting
    // get the hair cut
    }
    else {
    // No empty seats => leave
    signal(mutex) ;
    }
    }
    }

    void Barber() {
    while (true) {
    /*
    Is there any customer waiting
    (check current customers)
    No customers => sleep
    */
    wait(customers) ;
    /*
    some customers =>
    select a customer
    and cut hair for him
    */
    wait(mutex) ;
    waiting -- ;
    signal (barber) ;
    signal(mutex) ;
    // cut the hair
    } // Finish cutting
    }

    流程图:

    老师所给PPT解法:

  • 相关阅读:
    HDU1026 Ignatius and the Princess I
    luogu_1865 A % B Problem
    luogu_1092 虫食算
    luogu_1111 修复公路
    luogu_1265 公路修建
    luogu_2330 [SCOI2005]繁忙的都市
    luogu_1613 跑路
    luogu_3386 【模板】二分图匹配
    luogu_3388 【模板】割点(割顶)
    luogu_2327 扫雷
  • 原文地址:https://www.cnblogs.com/diyingyun/p/2275240.html
Copyright © 2011-2022 走看看