PV操作每日一题-缓冲区问题


时间紧,任务重。让我们继续奋斗PV操作的题目⑧!

一、问题描述

有n个进程将字符逐个读入到一个容量为80的缓冲区中(n>1),当缓冲区满后,由输出进程Q负责一次性取走这80个字符。这种过程循环往复,请用信号量和PV操作写出N个读入进程(P1,P2,…,Pn)和输出进程Q能正确工作的动作序列。


二、问题求解

char Buffer[80];        //容量为80的缓冲区
int count=0;            //计数
semaphore empty=80;     //缓冲区剩余容量
semaphore full=0;        //缓冲区是否满了
semaphore mutex=1;       //互斥访问缓冲区

Producer-i(i=12...,n)
{
    
    
    while(1)
    {
    
    
        str=getStr();//生产一个字符给str
        P(empty);
        P(mutex);
        Buffer[count++]=str;
        if(count==80)
        {
    
    
            V(full);
        }
        V(mutex);
    }
}

Q()
{
    
    
    while(1)
    {
    
    
        P(full);
        P(mutex);
        for(int i=0; i<80; i++)
        {
    
    
            read(Buffer[i]);
        }//利用循环实现Q进程一次性读走80个字符
        count=0;
        for(int i=0; i<80; i++)
        {
    
    
            V(empty);
        }
        V(mutex);
    }
}


今天的问题比较简单,重点是能不能理解各个信号量的意义,这是key!溜啦~

おすすめ

転載: blog.csdn.net/liangsena/article/details/121276032