当前位置:网站首页>PV operation daily question - orange apple question (advanced version)

PV operation daily question - orange apple question (advanced version)

2022-06-10 10:46:00 liangsena


Finally, we have to wait for the advanced version , Come on !

One 、 Problem description

There is a plate on the table , It can hold up to two fruits , Only put or take out at a time A fruit , Dad put apples on the plate , Mom put oranges on the plate , Two people required alternate Add fruit ; Yes Two sons and two daughters , My son eats one orange at a time , My daughter eats one apple at a time . Please use semaphores and PV Operate to solve the problem .

The change of the title is nothing more than :
1. The buffer size is 2, stay 1 and N Between
2. Alternate the fruit , Do not put the same fruit twice in a row
( A topic will be updated later , There are no restrictions on alternate placement , For the time being, it is called a higher-order variant )


Two 、 problem solving

semaphore singal=1;         // Two people put in the fruit alternately 
semaphore mutex=1;
semaphore appleFull=0;
semaphore orangeFull=0;
semaphore appleEmpty=1;
semaphore orangeEmpty=1;

// In fact, this problem can be seen as two people accessing two sizes of... Respectively 1 Orange and apple buffers 
// Take it apart and make it 

Father()
{
    
    while(1)
    {
    
        P(singal);
        P(appleEmpty);
        P(mutex);
         Put in an apple ;
        V(mutex);
        V(appleFull);       // Tell the two daughters : You can eat apples 
        V(singal);          // Send a signal to mom : You can put oranges 
    }
}

Mother()
{
    
    while(1)
    {
    
        P(singal);
        P(orangeEmpty);
        P(mutex);
         Put in an orange ;
        V(mutex);
        V(orangeFull);       // Tell the two sons : You can eat oranges 
        V(singal);          // Send a signal to Dad : You can put apples 
    }
}

Son-i(i=1,2)
{
    
    while(1)
    {
    
        P(orangeFull);
        P(mutex);
         Take an orange ;
        V(mutex);
        P(orangeEmpty);
    }
}

Datughter-i(i=1,2)
{
    
    while(1)
    {
    
        P(appleFull);
        P(mutex);
         Take an apple ;
        V(mutex);
        V(appleEmpty);
    }
}

See here , Maybe someone is confused , But don't be afraid of , Experience it over and over again PV The subtlety of the operation ~


3、 ... and 、 reflection

Imagine , Let two daughters or two sons mutually exclusive to get fruit ?
Is it necessary to set another semaphore ?

That's all for today , Slip away ~

原网站

版权声明
本文为[liangsena]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101014233215.html