Peterson Algorithm简介(Wikipedia)
Peterson’s algorithm (or Peterson’s solution) is a concurrent programming algorithm for mutual exclusion that allows two or more processes to share a single-use resource without conflict, using only shared memory for communication. It was formulated by Gary L. Peterson in 1981.[1] While Peterson’s original formulation worked with only two processes, the algorithm can be generalized for more than two.
实现的伪代码:
//shared variables
//who can enter critical section
int turn = 0
//who intend to enter critical section
boolean intendToenter[0] = true
//P0
while (true){
intendToEnter[0] = true
turn = 1
while(intendToEnter[1] && turn==1){/*busy wait*/}
critical section
intendToEnter[0] = false
non-critical section
}
//P1
while (true){
intendToEnter[1] = true
turn = 0
while (intendToEnter[0] && turn==0){/*busy wait*/}
critical section
intendToEnter[1] = false
non-critical section
}
//通用版本
//事件i和j是互斥的
//i + j = 1
do{
intendToEnter[i] = true
turn = j
while (intendToEnter[j] && turn==j){/*busy wait*/}
critical section
intendToEnter[i] = fase
noitical section
}while (true)
根据临界区问题的定义, 临界区问题的解答必须满足以下三点:
- 互斥成立
- 前进要求满足
- 有限次等待满足
1)互斥证明:
观察P0, 如果P0在临界区, 那么一定有intendToEnter[0]==true或者turn==0, 很显然这样的条件会使得P1无法结束等待循环.所以互斥成立.
2)满足前进要求证明:
观察P0, 即是说当P0不在临界区执行时, 如果P1打算在临界区执行, 那么经过有限次等待后,P1能够执行.
显然, P1永远会在临界区执行完一次之后, 又会进入进入区等待执行临界区, 而当P0离开临界区之后,P1就不满足等待条件,会进入临界区, 此时P0进入等待, 如此循环往复.
3)有限次等待满足要求
在2)中已经有说明.
总结:
Peterson算法适合两个共享资源的进程交替执行的协同控制.