問題描述
五個哲學(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ù)量