PV原語和哲學(xué)家吃面問題

問題描述

五個哲學(xué)家圍坐在一張圓桌旁,桌子中央一盤通心面(面假設(shè)無限),每個人面前有一只空盤,每兩個人之間放一把叉子。為了吃面,每個哲學(xué)家都必須獲得兩把叉子,且只能從自己左邊或右邊取

存在問題

假如五個哲學(xué)家同時拿起右手邊的叉子,那么五個人都將等待相鄰哲學(xué)家手中的叉子,出現(xiàn)“死鎖”。PV原語講解決死鎖問題。

java版本實(shí)現(xiàn)

未解決死鎖

Semaphore[] forks= new Semaphore[]{new Semaphore(1),new Semaphore(1),new Semaphore(1),new Semaphore(1),new Semaphore(1)};
        for(int i=0;i<5;i++){
            final int index=i;
            new Thread(()->{
                while(true){
                    try {
                        forks[index].acquire(); //P(index)
                        forks[(index+1)%5].acquire();//P((index+1)%mod5)
                        System.out.println("第"+index+"個哲學(xué)家在通心粉");
                        forks[index].release();
                        forks[(index+1)%5].release();
                        System.out.println("第"+index+"個哲學(xué)家吃完了");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

解決死鎖

Semaphore[] forks= new Semaphore[]{new Semaphore(1),new Semaphore(1),new Semaphore(1),new Semaphore(1),new Semaphore(1)};
        Semaphore limit = new Semaphore(4);
        for(int i=0;i<5;i++){
            final int index=i;
            new Thread(()->{
                while(true){
                    try {
                        limit.acquire();
                        forks[index].acquire(); //P(index)
                        forks[(index+1)%5].acquire();//P((index+1)%mod5)
                        System.out.println("第"+index+"個哲學(xué)家在通心粉");
                        forks[index].release();
                        forks[(index+1)%5].release();
                        limit.release();
                        System.out.println("第"+index+"個哲學(xué)家吃完了");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

PV原語

PV原語通過操作信號量來處理進(jìn)程間的同步與互斥的問題。其核心就是一段不可分割不可中斷的程序。 信號量的概念1965年由著名的荷蘭計算機(jī)科學(xué)家Dijkstra提出,其基本思路是用一種新的變量類型(semaphore)來記錄當(dāng)前可用資源的數(shù)量

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容