当前位置:网站首页>PV operation daily question - black and white chess question

PV operation daily question - black and white chess question

2022-06-10 16:10:00 liangsena


reminder , The code for this topic may be very simple , But a little around , Similar to the problem of orange and apple in the front, add the fruit alternately . All right. , Start !

One 、 Problem description

There is a box with an equal number of black and white chessmen , Now use the automatic sorting system to separate the black and white pieces , There are Two processes P1 and P2.P1 Responsible for sorting white chess pieces ,P2 Is responsible for sorting the black chess pieces , The two must be sorted alternately , And it shall not be stopped before the end of sorting . use PV Operation solves the problem .

Two 、 problem solving

: So to understand , hold P1 and P2 As two resources , Mutually exclusive access , Contrary to the orange apple problem .

semaphore flag1=1;
semaphore flag2=0;

P1()
{
    
    while(1)
    {
    
        P(flag1);
         Sort a white piece ;
        V(flag2);           // Signal to P2
    }
}

P2()
{
    
    while(1)
    {
    
        P(flag2);
         Sort a black piece ;
        V(flag1);           // Signal to P1
    }
}

3、 ... and 、 twitter

After understanding , After reading the code, do you think the title is super simple ~

原网站

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