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解法:

  • 相关阅读:
    laravel实现第三方登录(qq登录)
    laravel实现发送qq邮件
    第一个微信小程序(实现点击一个按钮弹出toast)
    Android笔记: 实现手机震动效果
    Android笔记: ListView基本用法-ArrayAdapter
    自适应网页设计
    javaWeb中,文件上传和下载
    jquery attr()方法
    jsp中的JSTL与EL表达式用法
    html中的事件属性
  • 原文地址:https://www.cnblogs.com/diyingyun/p/2275240.html
Copyright © 2011-2022 走看看