什麼是Peterson解法?
Peterson解法確保了互斥。它在使用者模式下實現,不需要任何硬體支援,因此可以在任何平臺上實現。Peterson解法使用兩個變數:`interested`和`turn`變數。
現在,我們將首先了解Peterson解法演算法,然後瞭解兩個程序P和Q如何使用Peterson解法實現互斥。
#define N 2
#define TRUE 1
#define FALSE 0
int interested[N]=False
int turn;
void Entry_Section(int process)
{
int other;
other=1-process
interested[process]= TRUE ;
turn = process;
while(interested[other]==TRUE && Turn=process);
}
void exit_section(int process)
{
interested[process]=FALSE;
}解釋
將有兩個程序,第一個程序的程序號=0,第二個程序的程序號=1。
因此,如果程序1呼叫`entry_section`,則`other` = 1-程序 = 1-1 = 0。
如果程序0呼叫,則`other` = 1-程序 = 1-0 = 1
現在,由於呼叫了`entry_section`的程序意味著該程序想要執行臨界區,則該程序將設定`interested[process]=TRUE`。
因此,如果程序1呼叫`entry_section`,則`interested[1]=TRUE`。
如果程序0呼叫`entry_section`,則`interested[0]=TRUE`。
宣告程序感興趣後,它將設定其`turn`。因此,如果呼叫程序1,則`turn = 1`。
然後,將執行`while (interested[other]==TRUE && Turn==process);`。
在這行程式碼中,程序檢查其他程序是否感興趣。如果該程序感興趣,則`interested[other]==TRUE`將為真,然後程序認為另一個程序可能正在執行臨界區。
為此,它將進入迴圈,直到另一個程序不再感興趣。現在,如果另一個程序變得感興趣,則`interested[other]==TRUE`
將變為假,並且程序將進入臨界區。因此,透過這種方式,只有一個程序可以進入臨界區。因此,在Peterson解法中保證了互斥。退出臨界區時,程序將`interest`設定為False。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP