进程同步 Process Synchroronization

Catalog Description

  1. Back Ground 

  2. The Critical-Section Problem

  3. Peterson's Solution

  4. Synchronization Hardware

  5.Semaphores

  6. Classic Problems of Sychronization

  7. Monitors

Back Ground

 

The processes are cooperating with each other directly or indirectly.

  Independent process cannot affect or be affected

  by the execution of another process  

Cooperating process can affect or be affected by

the execution of another process
Concurrent access (并发访问) to shared data
may result in data inconsistency(不一致)
for example: printer, shared variables/ tables/
lists
Maintaining data consistency requires mechanisms
to ensure the orderly execution of cooperating
processes

生产者消费者问题:生产者进程生产一个产品被消费者进程所消费

Solution1:Shared-Memory Solution  

我们假设这个生产者和消费者的内存是共享的(bounded-buffer),并且我们的共享内存区域是一个固定大小的内存区域:

Producer进程的代码:

1 while (true) {
2   /* produce an item and put in
3   nextProduced */
4   while (count == BUFFER_SIZE)
5     ; // do nothing
6   buffer [in] = nextProduced;
7   in = (in + 1) % BUFFER_SIZE;
8   count++;
9 }

Consumer进程的代码:

1 while (true) {
2   while (count == 0)
3     ; // do nothing
4   nextConsumed = buffer[out];
5   out = (out + 1) % BUFFER_SIZE;
6   count- -;
7   /* consume the item in nextConsumed*/
8 }

进程互斥产生的原因:

  是因为进程在宏观上并发执行,依靠时钟中断来实现微观上轮流进行

  访问共享资源

 

我们举一个简单的例子:现在有两个进程,读-修改-写(对于同一内存空间)

//Process 1         //Process 2
tmp1= count;       tmp2= count;
tmp1++;                tmp2= tmp2+2;
count= tmp1;           count= tmp2;                

 

那么请问:如果在这些进程执行之前,count变量的值为1,那么它最后的结果是多少?

很显然可能会出现以下三种情况~~

Case1:
//
Process 1       //Process 2 tmp1= count;(=1) //interrupt…                 tmp2= count;(=1)                 tmp2= tmp2+2;(=3)                  count= tmp2;(=3) tmp1++;(=2) count= tmp1;(=2) :
Case2:
//
Process 1         //Process 2                 tmp2= count;(=1)                 //interrupt… tmp1= count;(=1) tmp1++;(=2) count= tmp1;(=2)                 tmp2= tmp2+2;(=3)                 count= tmp2;(=3)
Case3:
//
Process 1         //Process 2 tmp1= count;(=1) tmp1++;(=2) count= tmp1;(=2)                 tmp2= count;(=)                 tmp2= tmp2+2;(=)                 count= tmp2;(=)

 

Race condition(竞争状态)

两个或多个进程对同一共享数据同时进行读写操作,而最后的结果是不可预测的,它取决于各个进程具体运行情况。

如何解决??:在同一时刻,只允许一个进程访问该共享数据,即如果当前已有一个进程正在使用该数据,那么其他进程不能访问。这就是互斥的概念。

 

竞争状态问题的抽象描述

把一个进程在运行过程中所做的事情分成两类

  进程内部的计算或其他的一些事情,肯定不会导致竞争状态的出现

  对共享内存或共享文件的访问,可能会导致竞争状态的出现。需要一些概念来进行描述、

 

竞争状态问题的抽象描述:

  把一个进程在运行过程中所做的事情分成两类进程内部的计算或其他的一些事情,肯定不会导致竞争状态的出现

  对共享内存或共享文件的访问,可能会导致竞争状态的出现。需要一些概念来进行描述

The Critical-Section Problem (临界区问题)

  临界区

转载于:https://www.cnblogs.com/nitrogenousfish/p/9959701.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值