Author : 张一极
20:55-20201025
中心 : 进程进入临界区的权限,只能由另一个进程赋予
初始化阶段,设置一个变量为允许进入临界区的进程flag:
xxxxxxxxxx11int flag_into_critical_section = 0;两个进程:
P1 :
x
1while(flag_into_critical_section!=0);2Get into critical section;//访问临界区,执行相应语句3flag_into_critical_section=1;//修改标志位4out the process;//outP2 :
xxxxxxxxxx41while(flag_into_critical_section!=1);//与P1的区别2Get into critical section;//访问临界区,执行相应语句3flag_into_critical_section=0;//修改标志位4out the process;//out解读:
一般情况一:
1.初始化标志位数据为0(使得p1可优先进入系统临界区)
2.执行p1,跳过循环语句,执行代码,执行完毕,退出,调度p2进入.
特殊情况一:
P2先调度进入系统,while函数是过不去的,此时只能等待P2退出(时间片用完)再调度P1,进行上述运行,接一般情况一
特殊情况二:
P1正常进入(包含P2调度消耗完时间片后调度P1),由于run期间,存在等待io等情况,如果未能将flag修改,便已经时间片用完,调度给P2,此时依然无法执行P2,只能等待时间片消耗,再返回P1.
问题:
只要存在P1不访问临界区的情况,会出现flag保持恒为0,此时无论什么时候调度到P2,都无法让它访问临界区,纵使现在进程是空闲的,浪费了系统资源.
新增数组bool flag[2];
x
1flag[0]=False;2flag[1]=False;//默认先设置为两个进程都不想进入临界区P1:
xxxxxxxxxx1while(flag[1]);2flag[0]=true;//P1想要进入临界区,防止P2进入临界区3Get into critical section;//访问临界区,执行相应语句4flag[0]=False;//修改标志位5out the process;//outP2:
x
1while(flag[0]);2flag[1]=true;//P2想要进入临界区,防止P1进入临界区3Get into critical section;//访问临界区,执行相应语句4flag[1]=False;//修改标志位5out the process;//out如果先执行while(flag[0]);紧接着发生调度,执行了while(flag[1]);那么会出现的情况就是,同时通过了while的循环,flag无意义,此时会出现共同访问的情况,违背临界区访问唯一性原则,原因是循环检查和锁定并非同时执行,前后可能出现进程切换.
P1:
xxxxxxxxxx1flag[0]=true;//P1想要进入临界区,防止P2进入临界区2while(flag[1]);3Get into critical section;//访问临界区,执行相应语句4flag[0]=False;//修改标志位5out the process;//outP2:
51flag[1]=true;//P2想要进入临界区,防止P1进入临界区2while(flag[0]);3Get into critical section;//访问临界区,执行相应语句4flag[1]=False;//修改标志位5out the process;//out同样,如果出现第一行语句同时执行,会出现,两个flag失效(all true),两个进程都无法访问临界资源.
End
21:12-20201025
晚安