Operating System-进程间互斥的方案-保证同一时间只有一个进程进入临界区(2)- Peterson解法...

本文接上一篇文章继续介绍如何实现同一时间只允许一个进程进入临界区的机制。本文主要介绍Peterson解法。

方案汇总

  1. 屏蔽中断
  2. 锁变量
  3. 严格轮换法
  4. TSL指令
  5. Peterson解法

一、Peterson解法

基于锁变量以及严格轮换的方法1981年,有位叫Peterson的大师提供了一个更加简单的方法来解决进程间互斥。

代码

#define N 2 //进程数为2
int turn;  //现在轮到哪个进程?
int interested[N]; //初始化置为false,即没有在临界区等待读写共享数据的

void enter_region(int process) //进入临界区
{
     turn = process;
     int other = 1 - turn; //另一个进程
     interested[turn] = true;
     while(turn == process && interested[other] == true)
                ; //一直循环,直到other进程退出临界区
}

void leave_region(int process)
{
     interested[process] = false;
}

代码非常精炼,主要通过两个变量来配合完成,一个turn和一个interested[]数组。

二、 代码分析

  • 只有process 0进入的时候:turn=0,other=1,interested[0]=true,interested[1]= false.  enter_region马上返回,process 0马上进入临界区。
  • process 0进入临界区,但还没有离开临界区,这个时候process 1进入了临界区,turn变成了1,interested[1]= true。other=0. 但是由于process 0还没有离开临界区,所以interested[0]=interested[other]一直还是true。那么这个时候process 1就会一直在enter_region中执行while,一直等待,直到process 0离开临界区把interested[0]设置为false。

考虑一个极端情况,Process 0和Process 1几乎同时调用了enter_region, 最终肯定有个线程把另外一个线程的数据给覆盖了,假定process 1覆盖了 process 0,那么这个时候turn是1。interested[0]=interested[1]=true.

  • process 0 会马上进入临界区,不执行while循环
  • process 1则会被block,因为这个时候 turn=1 && interested[0]=true,满足while循环。

这个代码真的非常尤美,不知道怎么形容,只能一遍一遍的来体会。

 

转载于:https://www.cnblogs.com/Brake/p/Operating_System_Solution_Of_Mutual_Exclusion_Part2.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值