进程同步03--Peterson算法

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. 互斥成立
  2. 前进要求满足
  3. 有限次等待满足

1)互斥证明:
观察P0, 如果P0在临界区, 那么一定有intendToEnter[0]==true或者turn==0, 很显然这样的条件会使得P1无法结束等待循环.所以互斥成立.

2)满足前进要求证明:
观察P0, 即是说当P0不在临界区执行时, 如果P1打算在临界区执行, 那么经过有限次等待后,P1能够执行.
显然, P1永远会在临界区执行完一次之后, 又会进入进入区等待执行临界区, 而当P0离开临界区之后,P1就不满足等待条件,会进入临界区, 此时P0进入等待, 如此循环往复.

3)有限次等待满足要求
在2)中已经有说明.

总结:
Peterson算法适合两个共享资源的进程交替执行的协同控制.

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值