首页计算机计算机软件计算机操作系统 04 第四章 互斥同步与通讯(1).pptx

04 第四章 互斥同步与通讯(1).pptx

页数:173页文件大小:523.6 KB来源: 计算机操作系统ppt课件

本课件从并发进程与临界区出发,比较软件与硬件互斥方案,重点讲解信号灯与P/V操作、生产者消费者、读者写者等经典同步问题,并介绍管程、会合、消息传递等高级同步与通信机制。

第四章互斥、同步与通信,给出相关结构设计与执行流程说明
4.1 并发进程,4.1.1前驱图的定义定义:前驱图是一个有向无环图
8 无前驱关系的程序段可以并发执行,4.1.1前驱图的定义例.对如下前驱关系:P1→P2, P1→P3,
查看本课件的文字版(共 173 页,供检索与复制)

第1页:第四章互斥、同步与通信

4.1并发进程( Concurrent Processes )4.2进程互斥( Mutual Exclusion )4.3进程同步( Synchronization )4.4进程高级通信( Communication )4.5系统举例

第2页:4.1 并发进程

4.1.1前驱图的定义定义:前驱图是一个有向无环图。图中每个结点表示一条语句、一个计算步骤或一个进程。结点间的有向边表示偏序或前驱关系“→”,关系→={(Pi,Pj)|Pi必须在Pj启动之前已经完成}(Pi,Pj)∈→记作Pi→Pj,称Pi是Pj的前驱,Pj是Pi的后继。前驱图中,没有前驱的结点称为初始节点;没有后继的结点称为终止节点。每个结点可以有权重,表示该结点的程序量或计算时间。偏序关系:具有反身性、反对称性、传递性。

第3页:8 无前驱关系的程序段可以并发执行

4.1.1前驱图的定义例.对如下前驱关系:P1→P2, P1→P3, P1→P4,P2→P5, P3→P5, P4→P5, P4→P6,P5→P7,P6→P7,P6→P8前驱图如下:P1P4P3P2P5P6P7P

第4页:1.程序的顺序性内部顺序性

  • 1.程序的顺序性内部顺序性:对一个进程来说,所有指令顺序执行;如有程序:S1: a:= x+y ;S2: b:= a-z ;S3: c:= a+b ;S4: d:=c+5 ;外部顺序性:多个进程依次执行(P82:图4-3)。4.1.2顺序程序及其特性该程序的内部顺序性的前驱图为:
  • 2.顺序程序设计的特性连续性:一个程序的指令连续执行,不会夹杂其它程序的指令;封闭行:程序执行过程中独占系统资源,不受其它程序影响;可再现性:给定初始条件,程序任意次执行得到相同结果。S1S2S3S4

第5页:5 内部并发性的前驱图

1.程序的并发执行内部并发性:指一个程序内部的并发性;如下程序段:S1: a := x+2;S2: b := y+4;S3: c := a+b;S4: d := c-6;S5: e := c+6;S6: f := c-e;外部并发性:多个程序的并发性。(P83:图4-5)4.1.3并发程序及其特性S1S2S3S6S4S

第6页:4.1.3 并发程序及其特性

  • 2.并发程序的特性考虑P、Q两个进程的并发执行进程P进程QA1:N = 0; B1: print(N);A2: N:= N+1; B2: N:= 0;A3: goto A2; B3: goto B1;显然:进程P、Q的不同并发执行,可得到不同结果。并发程序的特性:
    • 交叉性:并发执行可能会有多种交叉,会产生不同结果;
    • 非封闭性:进程运行环境会相互影响;
    • 不可再现性:交叉运行的随机性,会导致不同的运行结果。

第7页:4.1.4 程序并发执行的条件

    • 读集:R(Pi)={a1,a2,……,am}为Pi在执行期间所引用的所有变量的集合;
    • 写集:W(Pi)={b1,b2,……,bn}为Pi在执行期间所修改的所有变量的集合。
    • Bernstein条件:若程序(段)P1和P2满足如下条件:R(P1)∩W(P2)∪R(P2)∩W(P1)∪W(P1)∩W(P2)=φ则程序(段)P1和P2能够保持可再现性,因而可以并发执行。例:S1: a:=x-y;S2: b:=z+1;S3: v:=a+b;S4: w:=v+1;P1和p2无前驱关系。Bernstein条件为可并发必要条件,不是充分条件。

第8页:4.1.5并发程序的表示设S1、S2…

4.1.5并发程序的表示设S1、S2、……、Sn为n个程序段,则用如下形式的并发语句:cobegin S1; S2;……; Sn coend;或parbegin S1; S2;……; Sn parend;表示S1、S2、……、Sn的并发执行。遇到并发语句,系统会同时创建n个进程(线程)分别执行S1、S2、……、Sn。

第9页:4.1.6 与时间有关的错误终端

2:进程P2…………do{等待借书者;if x >= 1{x := x–1 ;借书} else无书}while(1);…………终端1:进程P1…………do{等待借书者;if x >= 1{x := x–1 ;借书} else无书} while(1);…………例:图书借阅系统(x:某种书册数,设当前x = 1)

第10页:4.1.6 与时间有关的错误

  • 错误原因:
    • 进程执行交叉(interleave) ;
    • 涉及公共变量(x)。
  • Remarks:
    • 某些交叉结果不正确;
    • 必须去掉导致不正确结果的交叉。

第11页:4.2 进程互斥

  • 4.2 进程互斥
  • 4.2.1 共享变量与临界区
  • 4.2.2 临界区域与进程互斥
  • 4.2.3 进程互斥的实现
  • 4.2.4 多处理机环境下的互斥

第12页:4.2 进程互斥(续)

  • 共享变量(shared variable)两个或两个以上的进程都需要访问的变量。
  • 临界区域(Critical Region)访问共享变量的程序段。4.2.1共享变量与临界区一组共享变量CR1CR2CRn……
  • 临界资源(Critical resource)一次只允许一个进程使用的资源。

第13页:4.2 进程互斥(续3)

  • 共享变量与临界区的表示共享变量:shared <一组变量>临界区域:region <一组变量> do <语句>也叫临界语句。4.2.1共享变量与临界区例子:shared x1,x2;shared y1,y2;regionx1,x2do {…………regiony1,y2do {…………}…………}

第14页:4.2 进程互斥(续4)

4.2.2临界区域与进程互斥进程互斥:两个或两个以上进程不能同时进入关于同一组共享变量的临界区域,否则可能发生与时间有关的错误,这种现象称为进程互斥。含义:⑴任何时刻最多只能有一个进程处于同一组共享变量的相同的临界区域;⑵任何时刻最多只能有一个进程处于同一组共享变量的不同的临界区域。Remarks:互斥是相对于公共变量而言的。

第15页:P1进程

  • P1进程:shared x1 , x2 ;region x1 , x2 do {…
  • ①…region y1 , y2 do{…….}…….};4.2.2临界区域与进程互斥嵌套临界区域(可能导致死锁)P2进程:shared y1 , y2 ;region y1 , y2 do {…
  • ②…region x1 , x2 do {…….}……} ;P1, P2在此处等待,出现死锁

第16页:P1进程(续)

临界区框架(Framework)Do {critical sectionremainder code} while(1);entry sectionexit section4.2.3进程互斥的实现实现互斥就是要编写entry section和exit section两部分。

第17页:4.2.3 进程互斥的实现

  • 临界区管理原则⑴互斥性(mutual exclusion)任一时刻至多只能有一个进程处于关于同一组共享变量的临界区中。⑵进展性(progress)临界区空闲时,保证执行entry section和exit section的进程参与下一个进入临界区进程的决策,该决策应该在有限时间完成。⑶有限等待性(bounded waiting)一个想要进入临界区的进程应当在有限等待时间内获得进入临界区的机会。

第18页:4.2.3 进程互斥的实现(续)

  • 临界区调度原则:⑴当关于某组共享变量的所有临界区空闲时,一个要求进入该临界区的进程应当能立即进入;⑵当关于某组共享变量的某一临界区被占用,所有要求进入关于该组共享变量的临界区的进程应当等待;⑶当一个进程离开某临界区时,应当允许某等待进入相关临界区的进程进入。进程互斥的可以软件方法实现,也可以硬件方法实现。

第19页:4.2.3.1 进程互斥的软件实现

  • 完全用程序实现,不需特殊硬件指令支持;
  • 可用于单CPU和多CPU环境中;
  • 有忙式等待问题。Busy waiting“运行”或“就绪”

第20页:4.2.3.1 进程互斥的软件实现(续)

(1) Dekker互斥算法int flag[ 2 ]; int turn; P0进程:do{flag[0]=1;whlie (flag[1]) doif(turn==1) {flag[0]=0;whlie(turn==1) do continue;flag[0]=1;}临界区;turn=1;flag[0]=0;其余代码;}while(1)P1进程:do{flag[1]=1;whlie (flag[0]) doif(turn==0) {flag[1]=0;whlie(turn==0) do continue;flag[1]=1;}临界区;turn=0;flag[1]=0;其余代码;}while(1)实现两个进程互斥的软件解法。

第21页:4.2.3.1 进程互斥的软件…(续3)

(2) Peterson互斥算法int flag[ 2 ]; int turn; P0进程:do{flag[0]=1; turn=1;whlie (flag[1]&&turn==1) docontinue;临界区;flag[0]=0;其余代码;}while(1)实现两个进程互斥的软件解法。P1进程:do{flag[1]=1; turn=0;whlie (flag[0]&&turn==0) docontinue;临界区;flag[1]=0;其余代码;}while(1)

第22页:4.2.3.1 进程互斥的软件实现

  • (3) Lamport面包店算法
  • 问题描述:
    • 顾客进面包店先抓号(号可能重复) ;
    • 按号码从小到大次序进店买面包;
    • 如号重复,按顾客名字的字典顺序进入。(假定名字不重复)
  • 算法思想:
    • 进程进入临界区前先选号;
    • 选号后按号从小到大的次序依次进入临界区;
    • 若不同进程选到相同的号,按进程编号依次进入。Definition:(a,b)<(c,d) if (a<c)or(a=c and b<d)

第23页:4.2.3.1 进程互斥的软件实现(续)

(3) Lamport面包店算法int choosing [ n ] = { 0, 0, 0, …… , 0 };int number [ n ] = { 0, 0, 0, ……, 0 };算法4.1 [ Pi进入]:choosing [ i ] = 1;number[ i ] = max{ number[0], …, number[n-1] }+1;choosing [ i ] = 0 ;for ( j = 0 ; j < n ; j++ ){while ( choosing [ j ] ) do continue;while (( number [ j ] != 0 ) &&(number [ j ], j ) < ( number [ i ], i )) do continue;}number[i] = 0;//Pi退出临界区C R

第24页:4.2.3.1 进程互斥的软件…(续3)

  • 例:P1选到1 ; P2选到1 ; P3选到2 ;正确次序:P1, P2, P3
  • 变量choosing的作用;
  • for循环中的两个while语句有忙式等待的情况;
  • 不进入等待状态的等待称为忙式等待(busy waiting).
  • 处于忙式等待状态的进程,其实际状态为运行或就绪。

第25页:4.2.3.1 进程互斥的软件实现

(4) Eisenberg-Mcguire算法数据结构:enum state { idle, want_in, in_cs } ;enum stateflag [ n ];intturn ;flag[i] == idle:进程Pi空闲,不想进入临界区;flag[i] == want_in:进程Pi想进入临界区;flag[i] == in_cs:进程Pi想进入或已进入临界区;

第26页:14.2.3.1 进程互斥的软件实现

进程Pi进入临界区算法思想(entry section):Step1:检查编号为turn, …, n-1, 0, 1, …, i-1的优先于Pi的进程是否空闲(idle),如不空闲则转Step1;Step2:依次检查编号从0~i-1, i+1, …, n-1的进程是否在临界区,如有任何一个进程在临界区,则转Step1;Step3:进入临界区turn=i .先于i先于i0iturnn-

第27页:4.2.3.1 进程互斥的软件实现

进程Pi退出临界区算法思想(exit section):Step1[找下一个竞争进程]从turn+1 (即i+1)开始找到一个非空闲( idle )的进程Pj ;Step2[指定下一个竞争进程j ]turn = j ;Step3[进程Pi退出临界区]flag [i] = idle .注意:Step1中,可能找到的j = i,即除进程Pi之外,其它进程都空闲。但由于Step3中将Pi的进程状态置为空闲idle ,能保证其它进程进入临界区。

第28页:Pi进入

Pi进入:do { flag [ i ] = want_in ; j = turn ;while ( j != i ) doif (flag [j] != idle )j = turn; else j = (j+1)%n ;flag [i] = in_cs ; j = 0 ;while ((j<n)&&(j == i||flag[j]!=in_cs )) do j++;}while ( j ! = n );turn = i ;C RPi离开:j = ( turn + 1 ) % n ;while ( flag [ j ] == idle ) do j = ( j + 1 ) % n;turn =j ;flag [ i ] = idle ;4.2.3.1进程互斥的软件实现(4) Eisenberg/Mcguire算法Pi进入的Step1.Pi进入的Step2.

第29页:4.2.3.2 进程互斥的硬件实现

(1)硬件提供“测试并设置”指令int test_and_set ( int *target ){ int temp;temp = *target ;*target = 1;return ( temp ) ;}

第30页:4.2.3.2 进程互斥的硬件实现(续)

    • 进程Pi :while ( test_and_set ( &lock )) do continue ;C Rlock = 0 ;
  • TS指令互斥的实现对一组公共变量,定义全局变量int lock = 0 ;不满足有限等待性

第31页:4.2.3.2 进程互斥的硬件…(续3)

  • 4.2.3.2进程互斥的硬件实现int waiting[n]={0,0,……,0}, lock=0;
    • 进程Pi :int key; waiting[i]=1; key=1;while(waiting[i]&&key) key=test_and_set(&lock);waiting[i]=0;C Rj=(i+1)%n;while ((j!=i)&&(!waiting[j])) do j=(j+1)%n;if (j==i) lock=0;else waiting[j]=0;
  • 满足有限等待性的TS互斥实现

第32页:4.2.3.2 进程互斥的硬件实现

(2)硬件提供“交换”指令void swap( int *a,*b){ int temp;temp = *a ;*a = *b ;*b = temp ;}

第33页:4.2.3.2 进程互斥的硬件实现(续)

  • SWAP指令互斥的实现对每一组公共变量,定义全局变量int lock=0;对要进入临界区的进程,定义局部变量int key;lock = 0 ;
    • 进程Pi :key = 1 ;do swap ( &lock, &key ) ;while ( key == 1 ) ;C R不满足有限等待性

第34页:4.2.3.2 进程互斥的硬件…(续3)

  • 满足有限等待性的SWAP互斥实现int waiting[n]={0,0,……,0}, lock=0;
    • 进程Pi :int key; waiting[i]=1; key=1;while(waiting[i]&&key) swap(&lock,&key);waiting[i]=0;C Rj=(i+1)%n;while ((j!=i)&&(!waiting[j])) do j=(j+1)%n;if (j==i) lock=0;else waiting[j]=0;

第35页:4.2.3.2 进程互斥的硬件实现

  • Remarks:
  • test_and_set指令和swap指令是原子的,不可中断的(在单CPU情况下) ;
  • test_and_set和swap实现互斥的方法都存在忙式等待;

第36页:4.2.3.2 进程互斥的硬件实现(续)

(3)硬件提供“关中断”和“开中断”指令关中断( CLI ){ Critical Region }开中断( STI )Remarks:⑴开/关中断只在单CPU系统中有效;⑵影响并发性;⑶效率高,无忙式等待,简单易行。

第37页:4.2.3.2 进程互斥的硬件…(续3)

  • 4.2.4多处理机环境下互斥⒈问题
  • 多CPU系统中,关中断对解决互斥无效;
  • 单CPU系统中指令间交叉,TS, swap指令是原子的;多CPU系统中指令周期间交叉,TS、swap指令占多个指令周期,不能保证其原子性,不同CPU上运行的进程可能同时访问一个单元。

第38页:4.2.3.2 进程互斥的硬件

4.2.4多处理机环境下互斥[问题例]多CPU下,test_and_set不能解决互斥。内存CPU2initial: 0Bus4. Write 13. Write 12. Read 01. Read 0lockCPU1

第39页:4.2.4 多处理机环境下互斥

  • First lock the bus:在执行TS指令和Swap指令前,首先锁总线(Bus-locking),以保证指令的原子性;执行完指令后再总线解锁(Bus-unlocking).
  • bus request protocol:modern buses have these facilities.earlier ones didn’t.

第40页:4.2.4 多处理机环境下互斥自旋锁

2.多CPU互斥的解决多CPU互斥算法:b = 1 ;while ( b ){ lock ( bus ) ;b = test_and_set ( &lock ) ;unlock ( bus ) ;}lock=0;CR

第41页:Assignment #1

  • Assignment #1
    • 进程切换时,下降进程的现场信息为何不能保存在系统栈中,而必须传送到PCB中?

第42页:Assignment #1(续)

3.Consider the following program:int blocked [ 2 ] ;int turn ; void P ( int id ){ do { blocked [ id ] = 1 ;while ( turn != id ) do{ while ( blocked [1-id ] )do continue;turn = id ;}<Critical Section>blocked [ id ] = 0 ;<Remainder>} whlie ( 1 ) ;}void main ( ){ blocked [ 0 ] = 0 ;blocked [ 1 ] = 0 ;turn = 0 ;parbeginP(0); P(1)parend ;}Assignment #1This is a software solution to the mutual exclusionproblem proposed byHyman. It is interesting to notethat even theCommunication of the ACMwas fooledon this one.Find a counter exampleto demonstrate that this solution is incorrect.

第43页:Assignment #1(续3)

3.Consider the following program:int blocked [ 1 ] ;int turn ; void P ( int id ){ do { blocked [ id ] = 1 ;while ( turn != id )do{ while ( blocked [1-id ] ) docontinue;turn = id ;}<Critical Section>blocked [ id ] = 0 ;<Remainder>} whlie ( 1 ) ;}Assignment #1当P(1)执行完第二个while,还未执行turn = id ;P(0)执行到第一个while。此时:turn=0,P(0)能进入CS;而P(1)执行完turn = id后,外层while条件为假,P(1)也能进入CS .P(1)执行完第二个while,还未执行turn = id ;P(0)执行到第一个while

第44页:4.3.1 进程同步的概念例

:司机—售票员问题⑴关门后才能启动汽车;⑵到站停车后方能开车门。4.3进程同步司机活动:do{启动车辆;正常行驶;到站停车;} while (1)售票员活动:do {关车门;售票;开车门;} while (1)

第45页:4.3.1 进程同步的概念定义

:一组进程,为协调其推进速度,在某些关键点处需要相互等待与相互唤醒,进程之间这种相互制约的关系称为进程同步,简称同步(Synchronization)。定义:一组进程,如果它们单独不能正常运行,但并发可以正常运行,称这种现象为进程合作(Cooperation)。参与合作的进程称作合作进程(Cooperating Process)。P1:synchronize先P2:后

第46页:4.3.1 进程同步的概念定义(续)

  • 4.3.2进程同步机制synchronization mechanism
  • 定义:用于实现进程同步的工具称为同步机制,亦称为同步设施。
  • 同步机制要求:
    • 描述能力够用;
    • 可实现;
    • 高效;
    • 使用方便。

第47页:4.3.2 进程同步机制

  • 典型同步机制
  • 信号量与P/V操作Semaphore and P/V operations
  • 条件临界区conditional critical region
  • 管程(monitor)
  • 会合(rendezvous)路径表达式(path expression)事件(traditional UNIX)

第48页:4.3.3信号量与P/V操作

  • 4.3.3信号量与P/V操作
  • E.W.Dijkstra, 1965.最成功、最早的进程同步机制;
  • 信号量是一种类型定义,其变量可以描述进程队列、资源以及进程互斥、同步等状况;
  • P/V操作是针对信号量变量定义的两种操作原语(类似于Atomic指令) ;
  • 一段不可间断执行的程序称为原语(Primitive) ;
  • 信号量变量可以看作共享变量,P/V操作是该共享变量的临界区;
  • 对P/V操作的互斥通常采用开/关中断的方法来实现。

第49页:4.3.3.1信号量与P/V操作的定义…

4.3.3.1信号量与P/V操作的定义⒈信号量类型的定义:typedef struct{ int value ;pointer_to_PCB queue ;} semaphore ;semaphores;Remarks:⑴semaphoreis pre-defined data type;⑵Variablescan be declared as needed .

第50页:信号量变量及进程队列例

信号量变量及进程队列例:semaphore S ;4.3.3.1信号量与P/V操作的定义S.valueS.queueS.valueS.queuePCBPCBPCB……FIFO

第51页:P操作原语

P操作原语:void P ( semaphore *s ){ s-> value--;if (s-> value < 0 )asleep (s-> queue);}asleep( s-> queue):⑴执行此操作进程的PCB入s-> queue的队尾(状态改为等待) ;⑵转处理机调度程序。Primitive: a piece of codeun-interruptible4.3.3.1信号量与P/V操作的定义

第52页:V操作原语

V操作原语:void V ( semaphore *s ){ s-> value ++ ;if (s-> value <= 0)wakeup (s->queue);}wakeup(s-> queue) :s-> queue链头PCB出等待队列,进入就绪队列(状态改为就绪)。4.3.3.1信号量与P/V操作的定义注意:P / V操作的参数S是指针型信号量,在调用P / V操作时其参数应该用&S取地址的形式,为简便起见,后面只用S的形式直接调用。

第53页:V操作原语(续)

  • 原语:一段不可间断执行的程序称为原语。规定和结论
  • 对于信号灯变量的规定:
    • 必须置一次初值,只能置一次初值,初值≥0 ;
    • 只能执行P操作和V操作,所有其它操作非法。
  • 几个有用的结论:
    • 当s.value≥0时, s.queue为空;
    • 当s.value<0时,∣s.value∣为队列s.queue的长度;
    • 当s.value初=1时,实现进程互斥;
    • 当s.value初=0时,可以实现进程同步;
    • 当s.value初=非1的正整数时,用于管理同种组合资源;4.3.3.1信号量与P/V操作的定义

第54页:V操作原语(续3)

  • 用“开关中断”实现的PV操作4.3.3.2信号量与P/V操作的实现void P(semaphore *s){disable interrupt; s->value--;if (s->value<0) {set process status to blocked;place this process in s->queue;enable interrupt; goto CPU dispatcher;}else enable interrupt; }asleep( )

第55页:V操作原语(续4)

  • 4.3.3.2信号量与P/V操作的实现void V(semaphore *s){disable interrupt; s->value++;if (s->value<=0) {remove a process from s->queue;place this process on ready list;}enable interrupt; }
  • 用“开关中断”实现的PV操作

第56页:V操作原语(续5)

  • 用“测试并设置”实现的PV操作4.3.3.2信号量与P/V操作的实现void P(semaphore *s){ while(TS(&(s->flag))); s->value--;if (s->value<0) {set process status to blocked;place this process in s->queue;s->flag=0; goto CPU dispatcher;} elses->flag=0; }

第57页:V操作原语(续6)

  • 4.3.3.2信号量与P/V操作的实现void V(semaphore *s){ while(TS(&(s->flag))); s->value++;if (s->value<=0) {remove a process from s->queue;place this process on ready list;}s->flag=0; }
  • 用“测试并设置”实现的PV操作

第58页:1.用信号量实现进程互斥问题描述

1.用信号量实现进程互斥问题描述:4.3.3.3信号量与PV操作的应用shared int x, y, z ;CR1CR2CRn

第59页:1.用信号量实现进程互斥问题描述(续)

  • 4.3.3.3信号量与PV操作的应用
  • 用信号量实现进程互斥实现原理:semaphore mutex; (初值mutex.value = 1 )P(mutex)CR1V(mutex)P(mutex)CR2V(mutex)P(mutex)CRnV(mutex)……shared int x , y , z ;

第60页:2.用信号灯实现进程同步问题描述

2.用信号灯实现进程同步问题描述:4.3.3.3信号量与PV操作的应用后动作P1:P2:先动作

第61页:2.用信号灯实现进程同步问题描述(续)

  • semaphore S ; ( initial s.value = 0 )
  • 用信号量实现进程同步实现原理:4.3.3.3信号量与PV操作的应用后动作P1:P2:先动作P ( S ) ;V ( S ) ;

第62页:借书系统互斥的实现

借书系统互斥的实现:Semaphore mutex ; ( initial mutex.value = 1 )终端1:do{等待借书者;P (mutex) ;if (x >= 1){ x = x–1 ;V(mutex);借书;}else {V(mutex);无书;}} while ( 1 )4.3.3.3信号量与PV操作的应用终端2:do{等待借书者;P (mutex) ;if (x >= 1){ x = x–1 ;V(mutex) ;借书;}else {V(mutex);无书;}} while ( 1 )

第63页:到站停车后方能开车门

4.3.3.3信号量与PV操作的应用例4-1:(同步例子)司机-售票员问题司机活动:售票员活动:do { do {启动车辆;关车门;正常行驶;售票;到站停车;开车门;} while (1) } while(1)要求:(1)关门后才能启动汽车;(

第64页:4.3.3.3信号量与PV操作的应用司…

4.3.3.3信号量与PV操作的应用司机-售票员问题的同步实现:semaphore s1 , s2 ; ( initial value 0 )司机活动:售票员活动:do { do {P ( S1 );关车门;启动车辆;V ( S1 );正常行驶;售票;到站停车;P ( S2 );V ( S2 );开车门;} while (1) } while(1)

第65页:4.3.3.3信号量与PV操作的应用司

  • Classical synchronization problems
  • 例4-2.Producers and consumers problem
  • 例4-3.Readers and writers problem
  • 例4-4.同种组合资源(3台打印机)的管理
  • 例4-5.Cigarette smokers problem
  • 例. Sleepy barbers problem4.3.3.3信号量与P/V操作的应用

第66页:4.3.3.3信号量与PV操作…(续)

例4-2.生产者/消费者问题预备知识:组合资源:若干相对独立的资源构成的资源集合,其中每个相对独立的资源称为子资源。同种组合资源:相同类型子资源构成的组合资源。同种组合资源的管理:semaphore S; (初值=子资源个数)例子:2台打印机semaphore S; S.value=2;申请打印机:P ( S );释放打印机:V ( S );

第67页:4.3.3.3信号量与PV操作

自动机描述2…10-1-2P(S)P(S)P(S)P(S)P(S)V(S)V(S)V(S)V(S)V(S)S.value=空闲资源数S.queue=空|S.value|=等待进程数空闲资源数=0...P(S):申请一台打印机,分配,空闲打印机减1;P(S):申请一台打印机,等待,等待进程数加1。例4-2.生产者/消费者问题

第68页:V(S)

V(S):释放一台打印机,唤醒一个等待者,打印机分给被唤醒进程,等待进程数减1;V(S):释放一台打印机,空闲打印机数量增1。自动机描述例4-2.生产者/消费者问题2…10-1-2P(S)P(S)P(S)P(S)P(S)V(S)V(S)V(S)V(S)V(S)S.value=空闲资源数S.queue=空|S.value|=等待进程数空闲资源数=0...

第69页:V(S)(续)

箱子B,容量kitem B [ k ] ;生产者生产物品放入B中B中取物品消费例4-2.生产者/消费者问题问题描述k-1……210消费者Producers and consumers problem,or bounded buffer’problem.

第70页:V(S)(续3)

环形缓冲区10K-1in(in+1)mod kout(out+1)mod k例4-2.生产者/消费者问题问题描述

第71页:生产者活动

生产者活动:消费者活动:do { do {加工一件物品;箱中取一物品;物品放入箱中;消耗这件物品;} while ( 1 ) } while ( 1 )例4-2.生产者/消费者问题问题分析资源:箱子(同种组合)资源:物品(同种组合)semaphore S1 ; semaphore S2 ;S1.value = k ; S2.value = 0 ;放前: P ( S1 )取前: P ( S2 )放后: V ( S2 )取后: V ( S1 )

第72页:生产者活动(续)

生产者活动:消费者活动:do { do {加工一件物品;P ( S2 ) ;P ( S1 ) ;箱中取一物品;物品放入箱中;V ( S1 ) ;V ( S2 ) ;消耗这件物品;} while ( 1 ) } while ( 1 )例4-2.生产者/消费者问题同步的实现对B和in,out的互斥:semaphore mutex ; ( mutex.value = 1 )

第73页:例4-2.生产者/消费者问题互斥的实现…

例4-2.生产者/消费者问题互斥的实现生产者活动:消费者活动:do { do {加工一件物品;P ( S2 ) ;P ( S1 ) ;P ( mutex ) ;P ( mutex ) ;箱中取一物品;物品放入箱中;V ( mutex ) ;V ( mutex ) ;V ( S1 ) ;V ( S2 ) ;消耗这件物品;} while ( 1 ) } while ( 1 )

第74页:例4-2.生产者/消费者问题互斥的实现

例4-2.生产者/消费者问题程序itemType buffer [ k ] ;semaphore S1, S2, mutex;int in, out;void producer ( ){ while(1){ produceItem(&item);P ( S1 ) ;P ( mutex ) ;buffer [ in ] = item;in = ( in + 1 ) % k;V ( mutex ) ;V ( S2 ) ;}}void consumer ( ){ while(1){ P ( S2 ) ;P ( mutex ) ;x = buffer [ out ] ;out = ( out + 1 ) % k;V ( mutex ) ;V ( S1 ) ;<consume x>;} while ( 1 ) ;}

第75页:例4-2.生产者/消费者问题互斥…(续)

void producer_consumer ( ){ S1.value = k ; S2.value = 0 ;mutex . value = 1 ;in = out = 0 ;fork ( producer, 0 ) ; … , fork ( producer, m-1 ) ;fork ( consumer, 0 ) ; … , fork ( consumer, n-1 ) ;}例4-2.生产者/消费者问题程序

第76页:例4-2.生产者/消费者问题互斥

例4-2.生产者/消费者问题并发性提高策略生产者和消费者:不操作buffer的相同分量生产者的共享变量:buffer [ in ] , in消费者的共享变量:buffer [ out ] , out并且in = out :满或空,semaphoremutex1 , mutex2 ; ( init 1 )

第77页:生产者活动

生产者活动:消费者活动:do { do {加工一件物品P ( S2 ) ;P ( S1 ) ;P ( mutex2 ) ;P ( mutex1 ) ;箱中取一物品物品放入箱中;V ( mutex2 ) ;V ( mutex1 ) ;V ( S1 ) ;V ( S2 ) ;消耗这件物品} while ( 1 ) } while ( 1 )例4-2.生产者/消费者问题并发性提高策略

第78页:生产者活动(续)

例4-3.读者/写者问题P. T. Courtois 1971. Communication of the ACM, Vol.14, 667-669.ACM:Association for Computing Machinery要求:⑴R–R可以同时;⑵R–W不可同时;⑶W–W不可同时。Problem Statement:accessingReaders and writers problemR1RmW1Wn共享数据

第79页:生产者活动(续3)

semaphore r_w_w ; ( init value: 1 )void reader ( ) void writer ( ){ P ( r_w_w ) ; { P ( r_w_w ) ;<read operations> <write operations>V ( r_w_w ) ; V ( r_w_w ) ;} }例4-3.读者/写者问题Solution1:不考虑R-R不互斥分析:不满足要求⑴,即R–R不能同时。改进:最先进入的R执行P ;最后离开的R执行V ;

第80页:int readCount = 0

int readCount = 0 ; ( initial value is 0 )void reader ( ){ readCount ++ ;if ( readCount == 1 ) P ( r_w_w ) ;<read operations>read_count--;if ( readCount == 0 ) V ( r_w_w ) ;}问题:对readCount操作的互斥问题。例4-3.读者/写者问题Solution2:考虑R-R不互斥

第81页:int readCount = 0(续)

semaphore mutex = 1 ;int readCount = 0 ;void reader ( ){P ( mutex ) ;readCount ++ ;if ( readCount == 1 ) P ( r_w_w ) ;V ( mutex ) ;<read operations>P ( mutex ) ;readCount--;if ( readCount == 0 ) V ( r_w_w ) ;V ( mutex ) ;}例4-3.读者/写者问题Solution2:考虑R-R不互斥

第82页:int readCount =…(续3)

void writer ( ){ while (1) {<other actions>P ( r_w_w ) ;<write operations>V ( r_w_w ) ;<othes actions>}}例4-3.读者/写者问题程序

第83页:int readCount =

void reader ( ){ while (1) {<other actions>P ( mutex ) ;readCount ++ ;if ( readCount == 1 ) P ( r_w_w ) ;V ( mutex ) ;<read operations>P ( mutex ) ;readCount--;if ( readCount == 0 ) V ( r_w_w ) ;V ( mutex ) ;<other actions>}}例4-3.读者/写者问题程序

第84页:int readCount =(续)

int readCount = 0 ;semaphore r_w_w . value = 1 ;semaphore mutex . value = 1 ;void reader_writer ( ){ cobeginfork ( reader, 0 ) ; …… fork ( reader, m-1 ) ;fork ( writer, 0 ) ; …… fork ( writer, n–1 ) ;coend}例4-3.读者/写者问题程序

第85页:int readCount =(续3)

问题:读者源源不断,readCount不归0 ,写者会被饿死,即饥饿(starvation)。策略:一旦有写者等待,新到达读者等待,正在读的读者都结束后,写者进入,即写者优先。例4-3.读者/写者问题程序分析

第86页:int readCount =(续4)

semaphore r_w_w=1, mutex=1,mutex1=1,read_q=1;int readCount=0, writeCount=0 ;void writer ( ){P ( mutex1 ) ;writeCount ++ ;if ( writeCount == 1 )P ( read_q );V ( mutex1 ) ;P ( r_w_w ) ; <write oerationps> V ( r_w_w ) ;P ( mutex1 ) ;writeCount--;if ( writeCount == 0 )V ( read_q );V ( mutex1 ) ;}例4-3.读者/写者问题Solution3:写者优先

第87页:int readCount =(续5)

void reader ( ){P ( read_q );P ( mutex ) ;readCount ++ ;if ( readCount == 1 ) P ( r_w_w ) ;V ( mutex ) ;V ( read_q )<read operations>P ( mutex ) ;readCount--;if ( readCount == 0 ) V ( r_w_w ) ;V ( mutex ) ;}例4-3.读者/写者问题Solution3:写者优先

第88页:enum state

enum state {free,used} ;enum state lp [ 3 ] ;semaphore S ;semaphore mutex ;例4-4.三台打印机管理int require ( ){P (S) ;P (mutex) ;for (i = 0; i<3; i++)if (lp[i]==free) break;lp[i] = used ;V (mutex) ;return (i) ;}void release ( int i ){ P (mutex);lp [i] = free ;V (mutex);V (S) ;}注意:执行for循环时P (S)已经通过,一定存在空闲(free)的打印机i。

第89页:enum state(续)

例4-5.吸烟者问题Cigarette Smokers’ ProblemPatil S. S.Limitations and Capabilities ofDijkstra’s semaphore primitives for coordinationamong processes.MIT project MACComputation Structure Group Memo 57, MIT,Cambridge, Mass, 1977.

第90页:例4-5.吸烟者问题材料

例4-5.吸烟者问题材料:烟草、卷烟纸和火柴供应者:⑴不吸烟;⑵有足够多的烟草、卷烟纸和火柴;⑶每次随机地将三种材料的两种各一样放到桌子上,供有另一种材料的吸烟者吸烟。吸烟者:⑴每位吸烟者只有一种吸烟材料,且彼此拥有材料各不相同;⑵每位吸烟者需要三种材料齐全才能吸烟。问题:实现供应者和吸烟者之间的同步。房间内有一位材料供应者和

第91页:例4-5.吸烟者问题材料(续)

  • 3 supplier processes:X: suppliestobaccoandmatch;Y: suppliesmatchandwrapper;Z: supplieswrapperandtobacco.
  • 3 smoker processes:A: possesstobacco;B: possessmatch;C: possesswrapper.例4-5.吸烟者问题Problem Statement⑴only one of X, Y, Z can supply at a time ;⑵X, Y, Z can proceed only after consumption .

第92页:例4-5.吸烟者问题材料(续3)

例4-5.吸烟者问题Traditional semaphoresemaphore tobacco ; semaphore match ; semaphore wrapper ; semaphore mutex ; 说明:⑴tobacco、match、wrapper分别表示烟草、火柴和卷烟纸的队列状况,并用于供应者与吸烟者之间的同步;⑵mutex用于X、Y、Z三个供应者之间的互斥。

第93页:例4-5.吸烟者问题材料(续4)

process XP(mutex);V(tobacco);V(match);process CP(tobacco);P(match);smoke;V(mutex);process AP(match);P(wrapper);smoke;V(mutex);process BP(wrapper);P(tobacco);smoke;V(mutex);process YP(mutex);V(match);V(wrapper);process ZP(mutex);V(wrapper);V(tobacco);Solution1:例4-5.吸烟者问题Traditional semaphore

第94页:Solution1存在的问题

Solution1存在的问题:供应者进程都供应特定的两种材料,并且分别供应给固定的吸烟者进程,Solution1存在另外两个吸烟者进程取单一材料的情况。解决方法⑴:某供应者进程执行(提供特定两种材料)时,应通知相应吸烟者进程;解决方法⑵:引进并发P、V操作SP和SV。semaphore mutex_A ; semaphore mutex_B ; semaphore mutex_C ; 解决方法⑴:例4-5.吸烟者问题Traditional semaphore

第95页:例4-5.吸烟者问题解决方法⑴

例4-5.吸烟者问题解决方法⑴:process XP(mutex);V(tobacco);V(match);V(mutex_C);process CP(mutex_C);P(tobacco);P(match);smoke;V(mutex);process AP(mutex_A);P(match);P(wrapper);smoke;V(mutex);process BP(mutex_B);P(wrapper);P(tobacco);smoke;V(mutex);process YP(mutex);V(match);V(wrapper);V(mutex_A);process ZP(mutex);V(wrapper);V(tobacco);V(mutex_B);

第96页:Semantics

Semantics:SP操作对多个信号量变量同时执行P操作。if∀i (1≤i≤n)Si.value≥dithenfor (i=1;i<=n;i++) Si= Si-di;else⑴place the executing process in the waitingqueue for the first Siwith Si<di;⑵set the program counter to the beginning ofthe SP operation so that all conditions will bereexamined when the process is reactivated.例4-5.吸烟者问题SimultaneousP-operationSyntax:SP ( S1[, t1, d1], … , Sn[, tn, dn]);其中:Si为信号灯变量, ti为Si的初始值, di为Si. value的增量值。

第97页:Semantics(续)

Semantics:if∀i (1≤i≤n)Si.value{ Si.value= Si.value + di;place all PCB in the Siqueue to the ready list ;}例4-5.吸烟者问题SimultaneousV-operationSyntax:SV ( S1, d1; … , Sn, dn);其中:Si为信号灯变量, di为Si. value的增量值。

第98页:例4-5.吸烟者问题解决方法⑵

例4-5.吸烟者问题解决方法⑵: SP操作semaphore tobacco, match, wrapper;semaphore mutex ;process Xdo {P(mutex);SV(tobacco,1;match,1);} while(1);process Ydo {P(mutex);SV(match,1; wrapper,1);} while(1);process Zdo {P(mutex);SV(wrapper,1; tobacco,1);} while(1);

第99页:例4-5.吸烟者问题解决方法⑵(续)

process CloopSP(tobacco,1;match,1);smoke; V(mutex);endloopprocess AloopSP(match,1;wrapper,1);smoke; V(mutex);endloopprocess BloopSP(wrapper,1;tobacco,1);smoke; V(mutex);endloop例4-5.吸烟者问题解决方法⑵: SP操作

第100页:例4-5.吸烟者问题解决方法⑵(续3)

  • 例4-5.吸烟者问题另一解法四个进程:
  • 供应者进程supplier随机提供所需两种材料;
  • 吸烟者进程smoker_A, smoker_B, smoker_C ;信号量定义:初值1,用于供应者互斥semaphoremutex;供应材料只有以下3种情况:初值均为0semaphoreA_smoke;semaphoreB_smoke;semaphoreC_smoke;X_smoke相当于供应者提供X吸烟者所需的2种材料。

第101页:进程描述

进程描述:void supplier ( ){ P (mutex ) ;V ( random ( A_smoke, B_smoke, C_smoke ) ) ;}void smoker_A ( ){ P (A_smoke); <A smoke>; V (mutex); }void smoker_B ( ){ P (B_smoke); <B smoke>; V (mutex); }void smoker_C ( ){ P (c_smoke); <c smoke>; V (mutex); }例4.吸烟者问题另一解法

第102页:进程描述(续)

  • 例.嗜睡理发师问题Sleepy barber’s problem理发店理有:⑴一位理发师;⑵一把理发椅;⑶n把供等候理发顾客坐的椅子;⑷理发店只有一扇门,一次只能进出一位顾客。
  • 如果没有顾客,理发师便在理发椅上睡觉;
  • 一个顾客到来时,它必须叫醒理发师;
  • 理发师正在理发时又有顾客来到,如果有空椅子可坐,就坐下来等待,否则就离开。

第103页:例.嗜睡理发师问题数据定义

例.嗜睡理发师问题数据定义:#defineCHAIRS10intwaiting=0;semaphorecustomers;semaphorebarbers;semaphoremutex;customers.value = 0;barbers.value = 0;mutex.value=1;

第104页:例.嗜睡理发师问题

例.嗜睡理发师问题void barber ( ){ while ( 1 ){ P(cutomers);P(mutex);waiting--;V(mutex);V(barbers);<cut-hair>;}}理发师进程:

第105页:例.嗜睡理发师问题(续)

例.嗜睡理发师问题void customer ( ){P (mutex);if ( waiting <CHAIRS){ waiting++;V (mutex);V (customers);P (barbers);<get_haircut>;}elseV ( mutex ) ;}顾客进程:

第106页:例.嗜睡理发师问题(续3)

4.3.4条件临界区Conditional Critical Region
背景
P/V操作低级,容易用错
条件临界区形式
region V when B do S ;
语义
没有任何其它进程处于与V相关的任何临界区内,当B为真时执行该语句的进程才能执行S。
Condition critical regions work as follows:1.A process wants to enter a region for S must obtain the mutex lock.If it cannot, then it is queued inmain queue.2.Once the lock is obtained,the boolean expression B is tested.If B evaluates toTRUEthen the process proceeds, otherwise it releases thelock , and is queued inevent queue.When it next gets the lock it must retest B.3.Each shared variable has two queuesassociatedwithit,eg. themain queueand theevent queue.Edison语言支持CCR同步机制。

第107页:4.3.4 条件临界区

  • 实现互斥:
    • regionvwhentruedos
  • CCR与P/V操作的等价性:
    • 用CCR可以实现P/V操作;
    • 用P/V操作可以实现CCR .
  • CCR执行效率低:由于B中可能包含局部变量,每次计算条件表达式B。

第108页:4.3.4 条件临界区(续)

4.3.4条件临界区CCR实现互斥例子void producer ( ){ do{<produce a product>P ( S1 ) ;V ( S2 ) ;} while ( 1 )}void consumer ( ){ do{ P ( S2 ) ;V ( S1 ) ;<consume x>;}while ( 1 )}P ( mutex ) ;B [ in ] =product;in = ( in + 1 ) % k;V ( mutex ) ;P ( mutex ) ;x = B [ out ] ;out = ( out + 1 ) % k;V ( mutex ) ;Region B when true do{ B [ in ] = product ;in = ( in + 1 ) % k; }Region B when true do{ x = B [ out ] ;out = ( out + 1 ) % k ; }

第109页:4.3.4 条件临界区例

4-6简单批处理中,作业输入、执行、打印结果三个部分同步的条件临界区程序实现。问题分析:作业的输入和执行涉及输入缓冲区的互斥和同步;作业的执行和打印涉及输出缓冲区的互斥和同步。Program batch;type buffer=recordslots: array[0..n-1] of T;head, tail: 0..n-1 initial (0,0);size: 0..n initial (0);end;var inbuff: buffer(cardimage);outbuff: buffer(lineimage);resource ib: inbuff; ob: outbuff;Cobeginprocess reader;var card: cardimage;loop<readcardfrom cardreader>regionibwheninbuff.size<ndoinbuff.slots[inbuff.tail]:=card;inbuff.size:=inbuff.size+1;inbuff.tail:=(inbuff.tail+1)mod n;enddoendloopendprocess

第110页:4.3.4 条件临界区例(续)

4.3.4条件临界区process executer;var card: cardimage;line: lineimage;loopregionibwheninbuff.size>0docard:=inbuff.slots[inbuff.head];inbuff.size:=inbuff.size-1;inbuff.head:=(inbuff.head+1)mod n;enddo<process card and generateline>regionobwhenoutbuff.size<ndooutbuff.slots[outbuff.tail]:=line;outbuff.size:=outbuff.size+1;outbuff.tail:=(iutbuff.tail+1)mod n;enddoendloopendprocessprocess printer;var line: lineimage;loopregionobwhenoutbuff.size>0doline:=outbuff.slots[outbuff.head];outbuff.size:=outbuff.size-1;outbuff.head:=(outbuff.head+1)mod n;enddo<printlineon lineprinter>endloopendprocesscoend

第111页:4.3.5 管程

  • (Monitor)信号量及P/V操作
  • 分散式同步机制:
    • 共享变量操作;
    • P/V操作分散在整个系统中或各个进程中。
  • 缺点:
    • 可读性差:P/V操作分散在各进程,操作的正确性要浏览整个程序;
    • 正确性不易保证:无法避免P/V操作的逻辑错误;
    • 不易修改:任意变量或代码的修改可能会影响全局。
  • 优点:高效,灵活。

第112页:4.3.5.1 管程的提出

  • 60年代末:Software Engineering; Structured programming.
  • 70年代初,E.W.Dijkstra, C.A.R.Hoare, P.B.Hansen.
  • 支持管程同步机制的并发语言(70年代~80年代初)
    • Concurrent Pascal (Hansen)
    • Modula (With)
    • Mesa
    • Mod*
    • Concurrent Euclid
    • XCY
  • 构造操作系统的PCM (Process, Class, Monitor)方法;如:Hansen用并发Pascal语言编写Solo操作系统。

第113页:4.3.5.1 管程的提出(续)

  • 基本思想:将共享变量及其所有操作集中在一个模块中。
  • 目的:
    • 把分散在各进程中的临界区集中起来进行管理;
    • 防止进程有意或无意的违法同步操作;
    • 便于用高级语言来书写程序,也便于程序正确性验证;
    • 共享性、安全性、互斥性。集中式同步工具

第114页:4.3.5.1 管程的提出(续3)

4.3.5.2管程形式type<monitor_name> =MONITOR;<共享变量说明>;define<本管程内定义的外部过程(函数)名表>;use<本管程外定义,本管程内使用的过程/函数名表>;procedure<过程名> (<形参表>);<局部变量说明>;begin <语句序列> end;…………function<函数名> (<形参表>) : <返回值类型>;<局部变量说明>;Begin <语句序列>End;……………begin <共享变量初始化语句序列>end;

第115页:4.3.5.2 管程形式

  • 外部过程(函数)管程内定义的过程(函数)的名字,如果出现在define的列表中,则该过程(函数)称为外部过程(函数)。
  • 局部过程(函数)管程内定义的过程(函数)的名字,如果未出现在define的列表中,则该过程(函数)称为局部过程(函数)。管程特点:⑴modularized:管程就是一个模块;⑵abstract data type:数据定义和对数据的操作;⑶information hiding:管程操作外部不可见。

第116页:4.3.5.2 管程形式管程例子共享变量

typeSSU=MONITOR;varbusy:boolean;busy_q:condition;definerequire,release;usewait,signal;procedurerequire();beginifbusy=truethenwait(busy_q);busy:=ture;end;procedurerelease();beginbusy:=false;signal(busy_q);end;beginbusy:=false;end

第117页:4.3.5.3 管程语义

  • 管程的共享变量在管程外部不可见,外部只能通过调用管程中的外部过程(函数)间接访问共享变量;
  • 为保证对共享变量操作的数据完整性,规定管程互斥进入;
  • 管程中有等待/唤醒机制:
    • 等待时释放管程的互斥权;
    • 唤醒时(如: P唤醒Q ),有3种处理方法:⑴P等待, Q运行,直到Q退出或等待; (Hoare)
    • signal and waiting⑵Q等待, P继续,直到P退出或等待; (Java)
    • Signal and continue
    • 被唤醒进程需要重新检查等待条件,可能再次等待。⑶唤醒是管程中可执行的最后一个操作。(Hansen)
    • Signal and leave

第118页:Hoare管程设施

Hoare管程设施
入口等待队列
每个管程变量一个,用于排队进入;
紧急等待队列
每个管程变量一个,用于唤醒等待;按策略⑴:n个进程P1、P2、…、Pn,若Pi唤醒Pi+1,则进程P1、P2、…,Pn-1进入紧急等待队列。
内部等待队列
条件型变量等待队列。
var c: condition;可根据需要定义多个,用于设置进程等待条件。4.3.5.3管程语义条件变量实际是指针变量,指向由于某种条件不成立使进程进入等待的进程队列,其初值为空。

第119页:4.3.5.3 管程语义管程队列

PCBPCBPCB…PCBPCBPCB…PCBPCBPCB…ConditionC1…………………………………ConditionCnUrgentPCBPCBPCB…Entry queueMonitor

第120页:4.3.5.3 管程语义条件变量操作

  • var c : condition ;
  • wait ( c ) :
    • 如果紧急队列非空,唤醒第一个等待者,否则释放管程互斥权;
    • 执行此操作的进程(线程)进入c链尾。
  • signal ( c ) :
    • 如c链空,相当空操作,执行此操作的进程继续。
    • 否则唤醒c队列的第一个等待进程,执行此操作的进程(线程)进入紧急队列尾部。

第121页:4.3.5.3 管程语义条件变量…(续)

4.3.5.3管程语义管程构成管程等待队列condition c1wait(c1)condition cn……………urgent queuesignal管程定义共享变量条件变量define、use列表过程(函数)1过程(函数)k……………初始化代码signal(c1)wait(cn)signal(cn)wait,结束入口等待队列

第122页:4.3.5.3 管程语义管程的进入和离开

  • 进入管程:
    • 申请管程互斥权。
  • 离开管程:
    • 如紧急等待队列非空,则唤醒第一个等待者;否则开放管程(唤醒入口等待队列第一个进程)。

第123页:4.3.5.4 管程的使用

  • 例4-7.读者/写者问题(偏向写者)
  • 例4-8.Disk head scheduling problem
  • 例4-9.Sleepy barber’s problem例.生产者/消费者问题例.哲学家就餐问题(another approach)例. Single resource management

第124页:4.3.5.4 管程的使用(续)

例4-7.读者/写者问题typereaders_and_writers= Monitor ;var rq , wq :condition;reading_count : integer ;write_count : integer ;definestart_read , finish_read ,start_write , finish_write ;

第125页:4.3.5.4 管程的使用(续3)

例4-7.读者/写者问题procedure start_read;beginif write_count > 0thenwait ( rq );reading_count ++;signal ( rq ) ;end ;procedure finish_read;beginreading_count--;if reading_count = 0thensignal ( wq );end ;写者优先

第126页:4.3.5.4 管程的使用(续4)

procedure start_writebeginwrite_count++;if (write_count>1) or(reading_count>0)thenwait ( wq );end ;procedure finish_writebeginwrite_count--;if write_count > 0thensignal ( wq );elsesignal ( rq );end ;例4-7.读者/写者问题写者优先

第127页:4.3.5.4 管程的使用(续5)

beginreading_count := 0 ;write_count := 0 ;end ;var rw :readers_and_writers;读者进程:rw.start_read;{reading}rw.finish_read;写者进程:rw.start_write;{writing}rw.finish_write;例4-7.读者/写者问题

第128页:4.3.5.4 管程的使用(续6)

  • 例4-8.磁头引臂调度问题0 1 …… 199updown磁头引臂扇区
  • 磁盘结构及其I/O方式:
  • 问题:有多个磁盘块的I/O请求时,如何进行I/O调度。

第129页:调度算法

  • 调度算法
  • FCFS (first come first serve)
    • 公平
    • 效率低(12,190,19,180,11,190,…)
  • SSTF (shortest seek time first)
    • 效率高
    • 磁道歧视
  • SCAN (elevator algorithm)
    • 效率较高,较公平例4-
  • 8.磁头引臂调度问题

第130页:例4-8.磁头引臂调度问题

  • 例4-8.磁头引臂调度问题
  • 电梯算法(elevator algorithm)也叫SCAN算法。是确定磁盘磁头引臂移动的I/O请求调度算法。
  • 原理:象电梯运行一样,磁头引臂从当前位置沿一个方向移动,直到在该方向的远端没有I/O请求为止,然后改变方向。

第131页:Hansen管程实现SCAN算法

Hansen管程实现SCAN算法:唤醒是管程中可执行的最后一个操作。外部过程:申请:require ( dest : 0 .. 199 )释放:release ( )使用方式:require ( dest ) ;{ I/O操作}(管程外操作)release ( ) ;例4-8.磁头引臂调度问题

第132页:Hansen管程实现SCAN算法(续)

typedisk_head_schedul= MONITOR ;var busy : boolean ;headpos : 0..199 ;direction : (up, down) ;cylinder : array[0..199] ofcondition;//每个磁道一个等待队列;count : array[0..199] of integer ;//每个磁道等待队列中等待I/O的进程个数;definerequire, release;例4-8.磁头引臂调度问题管程实现SCAN算法

第133页:Hansen管程实现SCAN算法(续3)

例4-8.磁头引臂调度问题管程实现SCAN算法procedure require ( dest: 0..199 ) ;beginif busy=true thenbegincount [dest]++ ;wait (cylinder[dest]);end;busy :=true;if dest < headposthen direction :=down;else if dest > headposthen direction :=up;headpos := dest ;end;根据dest和磁头当前位置headpos,确定磁头引臂动作方向。

第134页:Hansen管程实现SCAN算法(续4)

例4-8.磁头引臂调度问题管程实现SCAN算法procedure upscan;var i : 0 .. 200 ;begini := headpos ;while (i <= 199) and (count [ i ] = 0) do i++ ;if i <= 199 thenbegincount [i]--;signal ( cylinder [i] );endend;从当前磁头位置向内扫描,直到找到一个有I/O请求的磁道。唤醒i磁道等待I/O的一个进程,退出管程。

第135页:Hansen管程实现SCAN算法(续5)

例4-8.磁头引臂调度问题管程实现SCAN算法procedure downscan ;var i :-1 .. 199 ;begini := headpos ;while ( i >= 0 ) and (count [i] = 0) do i--;if i >= 0 thenbegincount [ i ]--;signal (cylinder [ i ] );endend;从当前磁头位置向外扫描,直到找到一个有I/O请求的磁道。唤醒i磁道等待I/O的一个进程,退出管程。

第136页:Hansen管程实现SCAN算法(续6)

procedure release ;beginbusy :=false;if direction =upthen beginupscan ; downscanendelse begindownscan ; upscanendend;例4-8.磁头引臂调度问题管程实现SCAN算法procedure initialize ;var i: 0..199;beginbusy :=false; headpos := 0; direction :=up;for i := 0 to 199 do count [ i ] := 0 ;endbegin initialize end;

第137页:Hansen管程实现SCAN算法(续7)

例4-9.嗜眠理发师问题…凳子(n个)理发椅理发店Sleepy barber’s problem

第138页:理发店里有

  • 理发店里有:⑴一位理发师;⑵一把理发椅;⑶n把供等候理发顾客坐的凳子;⑷理发店只有一扇门,一次只能进出一位顾客。
  • 如果没有顾客,理发师便在理发椅上睡觉;
  • 一个顾客到来时,它必须叫醒理发师;
  • 理发师正在理发时又有顾客来到,如果有空凳子可坐,就坐下来等待,否则就离开。例4-9.嗜眠理发师问题

第139页:理发店里有(续)

TYPEsleepy_barber= MONITOR ;VAR chair :condition;stool :condition;count : 0 .. n ;definesleep , enter , leave ;例4-9.嗜眠理发师问题procedure sleep ;beginif count = 0thenwait (chair);end ;procedure leave ;begincount := count-1 ;if count <> 0thensignal (stool);end ;

第140页:理发店里有(续3)

procedure enter (varfull : Boolean ) ;beginif count = nthen full :=true;else beginfull :=false;count := count + 1 ;if count = 1thensignal (chair);elsewait (stool);end ;end ;例4-9.嗜眠理发师问题

第141页:理发师活动

理发师活动:Repeatspy.sleep ;<Cut-hair> ;Until false ;顾客活动:Repeatspy.enter (full) ;Until not full ;<Cut-hair >;spy.leave ;例4-9.嗜眠理发师问题begin count :=0 ; endvar full : Boolean;(初值false)var spy : sleepy_barber;

第142页:理发师活动(续)

理发师活动:Repeatspy.sleep ;<Cut-hair>;spy.leave ;Until false ;顾客活动:Repeatspy.enter (full) ;Until not full ;<Cut-hair> ;例4-9.嗜眠理发师问题问题:当最后一位顾客理完发还没执行spy.leave,而理发师进程执行spy.sleep时,由于此时count=1,因此理发师进程又进入Cut-hair.

第143页:理发师活动(续3)

例.生产消费问题typeproducer_consumer= MONITOR;var B: array [ 0 .. n-1 ] of product ;count , in , out : integer ;pq , cq : condition ;define put_in , get_out ;procedure put_in ( item : product ) ;beginif count = n thenwait ( pq );B [ in ] := item ;in:= ( in + 1 ) mod n ;count++;signal (cq);end;

第144页:例.生产消费问题

例.生产消费问题procedure get_out ( var item : product )beginif count = 0 thenwait ( cq );item := B [ out ] ; out := ( out + 1 ) mod n ;count--;signal ( pq );end;begin in:=0; out:=0; count:=0; end;var pc: producer_consumer;生产者活动:do {加工一件物品item;pc.put_in ( item );} while ( 1 )消费者活动:do { pc.get_out ( item);消耗物品item;} while ( 1 )

第145页:例.哲学家就餐问题哲学家活动

例.哲学家就餐问题哲学家活动:repeat思考;L:取左叉;if右叉空闲thenbegin取右叉;进食;放左叉,放右叉;end;elsebegin放左叉; goto L;end;untilfalse

第146页:例.哲学家就餐问题哲学家活动(续)

例.哲学家就餐问题typedining_philosophers= MONITOR ;var fork: array[0..4] of (free, used) ;q: array[0..4] ofcondition;definepick_up, try_pick_up, put_down ;procedure pick_up (I: 0..4) ;beginif fork [I] =usedthenwait (q [I]);fork [I] :=used;end ;

第147页:例.哲学家就餐问题哲学家活动(续3)

function try_pick_up(I: 0..4): boolean ;beginif fork[I] =usedthentry_pick_up :=false;elsebeginfork[I] :=used;try_pick_up :=true;endend ;例.哲学家就餐问题

第148页:例.哲学家就餐问题哲学家活动(续4)

procedure put_down(I: 0..4) ;beginfork[I] :=free;signal (q [I]) ;end ;beginvar I: 0..4 ;for I := 0 to 4 do fork[I] :=free;end例.哲学家就餐问题

第149页:varforks

varforks :dining_philosophers;I号哲学家活动:repeat< thinking > ;with_two_forks := false ;repeatforks.pick_up (I) ;if forks.try_pick_up ((I+1) mod 5)thenwith_two_forks := true ;elseforks.put_down ( I ) ;untilwith_two_forks;例.哲学家就餐问题

第150页:<

< Eating > ;forks.put_down (I) ;forks.put_down ((I+1) mod 5) ;Until false;例.哲学家就餐问题问题:各哲学家总是同时拿左叉会出现饿死;

第151页:<(续)

例.单一资源管理typesingle_resource= MONITOR ;var busy : boolean ;queue : condition ;definerequire , release ;Single resourcemanagementprocedure require;beginif busy =truethenwait (queue );busy :=true;end ;procedure release ;beginbusy :=false;signal (queue );end;

第152页:begin busy

begin busy :=falseend ;var lp, tape : single_resource;申请tape :tape.require;释放tape :tape.release;例.单一资源管理PCBPCBPCB…lp.queuePCBPCBPCB…tape.queue申请lp :lp . require ;释放lp :lp . release ;

第153页:begin busy(续)

  • 4.3.5.5管程与P/V操作的等价性
  • 用管程可以构造P/V操作
  • 用P/V操作可以构造管程Implementing PV operationsusing monitors is trivial

第154页:begin busy(续3)

TYPE semaphore = MONITOR ( init_value );VAR c : condition ; count : integer ;defineP , V ;procedure V ;begincount := count + 1 ;if count <= 0then signal ( c ) ;end ;4.3.5.5管程与P/V操作的等价性⑴用管程构造P/V操作假定系统中已有管程同步机制,现用它构造P/V操作。procedure P ;begincount := count–1 ;if count < 0 then wait ( c ) ;end ;Procedure initbegin count:=init_value; end ;

第155页:管程信号量与P/V操作VAR s

管程信号量与P/V操作VAR s : semaphore ;VAR s : semaphore ;init s ( init_value ) ;s.Value := init_value ;s . P ;P ( s ) ;s . V ;V ( s ) ;4.3.5.5管程与P/V操作的等价性P/V操作与管程对应关系⑴用管程构造P/V操作

第156页:管程信号量与P/V操作VAR s(续)

信号量与PV操作管程一个入口等待队列mutex: semaphore(1)一个紧急等待队列urgent : semaphore (0)一个紧急等待计数urgent_count : integer(0)一个管程实例一个信号灯变量Sc: semaphore (0)一个计数变量c_count : integer (0)一个条件变量var c: condition;if urgent_count > 0thenbeginurgent_count--;V(urgent) ;endelse V(mutex);c_count++ ; P ( Sc ) ;等待操作wait ( c )4.3.5.5管程与P/V操作的等价性(1)用P/V操作构造管程

第157页:管程信号量与P/V操作VAR s(续3)

信号灯与PV操作管程if c_count > 0 thenbeginc_count--;V(Sc);urgent_count ++ ;P(urgent);end唤醒操作signal ( c )P ( mutex ) ;进入管程if urgent_count > 0then beginurgent_count--;V(urgent) ;endelse V ( mutex ) ;离开管程4.3.5.5管程与P/V操作的等价性(2)用P/V操作构造管程

第158页:4.3.5.6 管程嵌套调用问题

  • :
  • 1.是否允许嵌套;
  • 2.若允许,如何处理互斥权。方法:
  • 1.禁止嵌套(Modula)
  • 2.允许嵌套,等待时释放当前管程互斥权;
  • 3.允许嵌套,等待时释放所有管程互斥权;
  • 4.允许嵌套,调用时释放路经管程互斥权wait(c)P:M1...M2Mn-1Mn

第159页:4.3.5.6 管程嵌套调用问题(续)

  • 4.3.5.7 Java语言中的“管程”类似管程的对象object
  • 每个object有一个互斥锁lock,一般未用;
  • 说明为synchronized的method启用互斥锁;
  • 每个object内部有一个等待队列;
  • wait() :
    • 释放lock,状态改为blocked,进入wait set.
  • notify() :
    • 在wait set中取任意线程,移到entry set,状态改为runnable. (Signal and continue)
  • notifyAll
    • wait set所有线程移到entry set,状态改为runnable.

第160页:4.3.5.6 管程嵌套调用问题(续3)

Entry set and wait set4.3.5.7 Java语言中的“管程”ObjectLockownerentry setwait setAcquire locknotify, notifyAllwait

第161页:4.3.5.6 管程嵌套调用问题(续4)

  • entry setandwait set
  • 锁的持有者执行wait操作,状态改为blocked,释放所持有的锁,进入wait set ;若entry set非空,选择其一进入同步方法。
  • 锁的持有者执行notify操作,任选wait set上的一个线程,入entry set ,状态改为runnable .
  • 锁的持有者执行notifyAll操作,wait set上的所有线程出wait set ,入entry set ,状态改为runnable .4.3.5.7 Java语言中的“管程”

第162页:Java“管程”例1

Java“管程”例1:生产/消费问题public classBounded Buffer{ public BoundedBuffer ( ){ count=0; in=0; out=0;buffer = new Object [ BUFFER_SIZE ] ;}private static finalintBUFFER_SIZE=5;privateintcount, in, out;privateObject[]buffer;

第163页:Java“管程”例1(续)

publicsynchronizedvoid enter(Object item){ while ( count == BUFFER_SIZE )try{ wait();//被唤醒后重新检测等待条件}catch (InterruptedException e){ }count++;buffer [ in ] = item ;in = ( in+1 ) % BUFFER_SIZE ;notify ( ) ;}Java“管程”例1:生产/消费问题

第164页:Java“管程”例1(续3)

publicsynchronizedObject remove( ){ while ( count == 0 ){try{ wait();}catch (InterruptedException e){ }}count--;item = buffer [ out ] ;out = ( out + 1 ) % BUFFER_SIZE ;notify ( ) ;return ( item );}} Java“管程”例1:生产/消费问题

第165页:Java“管程”例1(续4)

Java“管程”例1:生产/消费问题生产者活动:do {加工一件物品item;pc.enter( item );} while ( 1 )消费者活动:do { item=pc.remove;消耗物品item;} while ( 1 )Bounded Bufferpc;

第166页:Java“管程”例1(续5)

public classDatabase{public Database ( ){ readcount = 0 ;dbReading = false ; dbWriting = false ;}private intreadercount;private booleandbReading;private booleandbWriting;Java“管程”例2:读者/写者问题

第167页:Java“管程”例1(续6)

publicsynchronizedvoid startRead( ){ while ( dbWriting == true )try{ wait ( ) ;}catch(InterruptedException e){}readcount ++ ;if ( readcount == 1 ) dbReading = true ;}publicsynchronizedvoid endRead(){ readcount--;if ( readcount == 0 ) dbReading = false ;notifyAll () ;}Java“管程”例2:读者/写者问题

第168页:Java“管程”例1(续7)

publicsynchronizedvoid startWrite( ){ while(dbReading==true||dbWriting==true)try{ wait();}catch (InterruptedException e) { }dbWriting=true;}publicsynchronizedvoid endWrite( ){dbWriting=false;notifyAll();}} Java“管程”例2:读者/写者问题

第169页:Java“管程”例1(续8)

  • Java synchronization rules
  • A thread that owns the lock for an object can enteranother synchronized method (or block) for the sameobject.
  • A method can nest synchronized method invocation fordifferent objects. Thus a thread can simultaneously ownthe lock for several different objects.
  • If a method is not declared as synchronized, then it canbe invoked regardless of lock ownership, even whileanother synchronized method for the same object isexecuting.
  • If the wait set for an object is empty, then a call to notify()or notifyAll() has no effect.

第170页:Java“管程”例1(续9)

Assignment #31. P143: #17,#182.用Hoare管程实现电梯算法。

第171页:Java“管程”例1(续10)

  • Windows2000/XP互斥同步机制
  • Mutex (OS API)
    • CreateMutex,//创建互斥对象,返回句柄
    • OpenMutex,//打开并返回存在对象句柄
    • ReleaseMutex;//释放对互斥对象的占用
  • semaphore (OS API)
    • CreateSemaphore,//创建信号量
    • OpenSemaphore,//返回已存在信号量句柄
    • ReleaseSemaphore;//释放对信号量的占用

第172页:Java“管程”例1(续11)

  • Event (OS API)
    • CreateEvent,
    • OpenEvent,
    • SetEvent,
    • ResetEvent,
    • PulseEvent.Windows2000/XP互斥同步机制

第173页:Java“管程”例1(续12)

  • CRITICAL_SECTION类型
    • InitializeCriticalSection:初始化
    • EnterCriticalSection:等待进入
    • TryEnterCriticalSection:非等待,失败返回0
    • LeaveCriticalSection:离开
    • DeleteCriticalSection:清除Windows2000/XP互斥同步机制
顶部目录