【进程&线程】临界区解决方法

来源:互联网 发布:网络看电视直播 编辑:程序博客网 时间:2024/05/29 17:17
大家都要用的变量叫临界区域(region)。
有几种手段可以避免ab线程一起进入临界区域:
1. 屏蔽中断
2. 锁变量
3. 严格轮换法
(前三个都有可能因为不是原子性操作而翻车)
4. Peterson解法(http://blog.csdn.net/martin31hao/article/details/8037455)
  1. #define N 2 //进程数为2
  2. int turn; //现在轮到哪个进程?
  3. int interested[N]; //初始化置为false,即没有在临界区等待读写共享数据的
  4. void enter_region(int process) //进入临界区
  5. {
  6. turn = process;
  7. int other = 1 - turn; //另一个进程
  8. interested[turn] = true;
  9. while(turn == process && interested[other] == true)
  10. ; //一直循环,直到other进程退出临界区
  11. }
  12. void leave_region(int process)
  13. {
  14. interested[process] = false;
  15. }

进程通信时无非会产生下列的两种情况:

1、进程0通信,进程1不影响。(反之亦然)

enter_region()中各参数的值:

turn = 0;

other = 1;

interested[0] = true;

interested[1] = false;

while循环直接在interested[other]那一步就退出了,进程0成功进入临界区。

一直循环是为了阻塞线程...但是有忙等待的缺点,浪费cpu。只是保证自己对临界区感兴趣,如果自己感兴趣并且另一个也感兴趣的话就只能空转cpu,消极等待。
0 0
原创粉丝点击