第七章

advertisement
Chapter 7: Process Synchronization
进程同步
背景
7.2 The Critical-Section Problem
临界区问题
7.3 Synchronization Hardware
同步的硬件实现
7.4 Semaphores
信号量
7.5 Classical Problems of Synchronization 经典同步问题
7.6 Critical Regions
临界区
7.7 Monitors
管程
7.8 OS Synchronization
操作系统的同步机制
7.9 Atomic Transactions
原子事务处理
 7.1 Background








Operating System Concepts
7.1
Silberschatz, Galvin and Gagne 2002
7.1 Background
背景
 Concurrent access to shared data may result in data
inconsistency.
对共享数据的并发访问可能导致数据的不一致性
 Maintaining data consistency requires mechanisms to
ensure the orderly execution of cooperating
processes.
要保持数据的一致性,就需要一种保证并发进程的正确执
行顺序的机制
Operating System Concepts
7.2
Silberschatz, Galvin and Gagne 2002
Background (Cont.)
 Shared-memory solution to bounded-butter problem
(Chapter 4) allows at most n – 1 items in buffer at the
same time. A solution, where all N buffers are used is
not simple.
第4章中解决有限缓冲区问题的共享内存方法…N项的缓冲
器最多只能使用n-1项
 Suppose that we modify the producer-consumer code
by adding a variable counter, initialized to 0 and
incremented each time a new item is added to the
buffer
假定我们通过增加一个计数器变量修改生产者-消费者代码
,初始值为 0,在缓冲区增加一个项目(数据)计数器加1
Operating System Concepts
7.3
Silberschatz, Galvin and Gagne 2002
Bounded-Buffer 有界缓冲区
 Shared data
#define BUFFER_SIZE 10
typedef struct {
...
} item;
item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
int counter = 0;
Operating System Concepts
7.4
Silberschatz, Galvin and Gagne 2002
Bounded-Buffer (Cont.-1)
 Producer process
item nextProduced;
while (1) {
while (counter == BUFFER_SIZE)
; /* do nothing */
buffer[in] = nextProduced;
in = (in + 1) % BUFFER_SIZE;
counter++;
}
Operating System Concepts
7.5
Silberschatz, Galvin and Gagne 2002
Bounded-Buffer (Cont.-2)
 Consumer process
item nextConsumed;
while (1) {
while (counter == 0)
; /* do nothing */
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
counter--;
}
Operating System Concepts
7.6
Silberschatz, Galvin and Gagne 2002
Bounded Buffer (Cont.-3)
 The statements
counter++;
counter--;
must be performed atomically.
 Atomic operation means an operation that
completes in its entirety without interruption.
Operating System Concepts
7.7
Silberschatz, Galvin and Gagne 2002
Bounded Buffer (Cont.-4)
 The statement “count++” may be implemented in
machine language as:
register1 = counter
register1 = register1 + 1
counter = register1
 The statement “count—” may be implemented as:
register2 = counter
register2 = register2 – 1
counter = register2
Operating System Concepts
7.8
Silberschatz, Galvin and Gagne 2002
Bounded Buffer (Cont.-5)
 If both the producer and consumer attempt to
update the buffer concurrently, the assembly
language statements may get interleaved.
如果生产者和消费者并发地更新缓冲区,汇编语言语句可
以得到的交替存取
 Interleaving depends upon how the producer and
consumer processes are scheduled.
交替取决于生产者和消费者进程如何调度
Operating System Concepts
7.9
Silberschatz, Galvin and Gagne 2002
Bounded Buffer (Cont.-6)
 Assume counter is initially 5. One interleaving of
statements is:
producer: register1 = counter (register1 = 5)
producer: register1 = register1 + 1 (register1 = 6)
consumer: register2 = counter (register2 = 5)
consumer: register2 = register2 – 1 (register2 = 4)
producer: counter = register1 (counter = 6)
consumer: counter = register2 (counter = 4)
 The value of count may be either 4 or 6, where the
correct result should be 5.
Operating System Concepts
7.10
Silberschatz, Galvin and Gagne 2002
Race Condition竞争条件
 Race condition: The situation where several processes
access and manipulate shared data concurrently. The
final value of the shared data depends upon which
process finishes last. Outcome of execution depends
on the particular order in which the access takes place.
竞争条件:若干进程并发地访问并且操纵共享数据的情况。
共享数据的值取决于哪个进程最后完成
 To prevent race conditions, concurrent processes must
be synchronized.
防止竞争条件,并发进程必须被同步
Operating System Concepts
7.11
Silberschatz, Galvin and Gagne 2002
7.2 The Critical-Section Problem
临界区问题
 n processes all competing to use some shared data
所有n 个进程竞争使用一些共享的数据。
 Each process has a code segment, called critical
section, in which the shared data is accessed.
每个进程有一个代码段, 称为临界区, 在那儿共享数据被访问.
临界区:访问临界资源的那段代码
 Problem – ensure that when one process is executing in
its critical section, no other process is allowed to
execute in its critical section.
问题- 保证当一个进程正在临界区执行时,没有另外的进程
进入临界区执行
 多个进程共享临界资源时必须互斥使用
Operating System Concepts
7.12
Silberschatz, Galvin and Gagne 2002
临界资源
多道程序环境->进程之间存在资源共享,进程的运行时间受影响
硬件或软件(如外设、共享代码段、共享数据结构),多个进
程在对其进行访问时(关键是进行写入或修改),必须互斥地
进行--有些共享资源可以同时访问,如只读数据
 进程间资源访问冲突
 共享变量的修改冲突
 操作顺序冲突
 进程间的制约关系
 间接制约:进行竞争--独占分配到的部分或全部共享资源,“互斥”
 直接制约:进行协作--等待来自其他进程的信息,“同步”
 临界资源:一次只允许一个进程使用(访问)的资源。如:硬件打印机、磁带机
等,软件的消息缓冲队列、变量、数组、缓冲区等。
Operating System Concepts
7.13
Silberschatz, Galvin and Gagne 2002
Solution to Critical-Section Problem must satisfy
解决临界区问题需满足
1. Mutual Exclusion: If process Pi is executing in its
critical section, then no other processes can be
executing in their critical sections.
互斥:假定进程Pi在其临界区内执行,其他任何进程将被排
斥在自己的临界区之外.
2. Progress:If no process is executing in its critical
section and there exist some processes that wish to
enter their critical section, then the selection of the
processes that will enter the critical section next
cannot be postponed indefinitely.
有空让进:临界区虽没有进程执行,但有些进程需要进入临
界区,不能无限期地延长下一个要进入临界区进程的等待时
间.
Operating System Concepts
7.14
Silberschatz, Galvin and Gagne 2002
Solution to Critical-Section Problem must satisfy (Cont.)
3. Bounded Waiting: A bound must exist on the number
of times that other processes are allowed to enter their
critical sections after a process has made a request to
enter its critical section and before that request is
granted.
有限等待: 在一个进程提出进入临界区的请求和该请求得到
答复的时间内,其他进程进入临界区前的等待时间必须是有
限的.
 Assume that each process executes at a nonzero
speed
假定每个进程都以非零的的速率执行.
 No assumption concerning relative speed of the n
processes.
没有任何关于这n个进程相对执行速率的假定
Operating System Concepts
7.15
Silberschatz, Galvin and Gagne 2002
同步机制应遵循的准则
 空闲让进。
当无进程进入临界区时,相应的临界资源处于空闲状态,因而允许
一个请求进入临界区的进程立即进入自己的临界区。
 忙则等待(互斥)。
当已有进程进入自己的临界区时,即相应的临界资源正被访问,
因而其它试图进入临界区的进程必须等待,以保证进程互斥地访问临
界资源。
 有限等待。
对要求访问临界资源的进程,应保证进程能在有限时间进入临界
区,以免陷入“饥饿”状态。
 让权等待。
当进程不能进入自己的临界区时,应立即释放处理机,以免进程
陷入忙等。
Operating System Concepts
7.16
Silberschatz, Galvin and Gagne 2002
解释: 使用临界区的原则
 每次只允许一个进程处于它的临界区(CS)中
 若有多个进程同时想进入CS,应在有限时间内让




其中一个进程进入CS,以免阻塞
进程在CS内只能逗留有限时间
不应使要进入CS的进程无限期地等待在CS之外
在CS之外的进程不可以阻止其他进程进入CS
不要预期和假定进程进展的相对速度以及可用的
处理器数目. 因为这是不可预期的.
Operating System Concepts
7.17
Silberschatz, Galvin and Gagne 2002
Fig 7.1 General structure of a typical process Pi
 General structure of process Pi (other process Pj)
do {





entry section
进入区
critical section
临界区
exit section
退出区
reminder section 剩余区
} while (1);
临界区(critical section):进程中访问临界资源的一段代码。
进入区(entry section):在进入临界区之前,检查可否进入临界区的
一段代码。如果可以进入临界区,通常设置相应"正在访问临界区"标
志
退出区(exit section):用于将"正在访问临界区"标志清除。
剩余区(remainder section):代码中的其余部分。
Processes may share some common variables to synchronize
their actions.
Operating System Concepts
7.18
Silberschatz, Galvin and Gagne 2002
7.2.1 Two-Process Solutions
Algorithm 1 (软件方法)
 Only 2 processes, P0 and P1
 Shared variables:
 int turn;
initially turn = 0
 turn = i  Pi can enter its critical section ( j=1-i)
 Process Pi
do {
while (turn != i) ;
critical section
turn = j;
reminder section
} while (1);
 Satisfies mutual exclusion, but not progress(不满足有空让进条件
)
Operating System Concepts
7.19
Silberschatz, Galvin and Gagne 2002
 问题:
 必须轮流使用临界区
 如果一个进程失败,另一个进程将被永久阻塞
 缺点:强制轮流进入临界区,没有考虑进程的实
际需要。容易造成资源利用不充分:在Pi出让临
界区之后,Pj使用临界区之前,Pi不可能再次使
用临界区;
Operating System Concepts
7.20
Silberschatz, Galvin and Gagne 2002
7.2.1.2 Algorithm 2
 Shared variables
 boolean flag[2];
initially flag [0] = flag [1] = false.
 flag [i] = true  Pi ready to enter its critical section
 Process Pi
do {
flag[i] := true;
while (flag[j]) ;
critical section
flag [i] = false;
remainder section
} while (1);
 Satisfies mutual exclusion, but not progress
requirement (see next page).
Operating System Concepts
7.21
Silberschatz, Galvin and Gagne 2002
7.2.1.2 Algorithm 2
 not progress requirement:
if 两个进程在执行while语句前, 同时执行了:
T0: P0 sets flag[0] := true
T1: P1 sets flag[1] := true
then
P0 and P1 are looping forever in their respective
while statements!
 也即:
Pi和Pj可能都进入不了临界区。当 Pi执行了flag[i] := true后, Pj执行了
flag[j] := true,这样两个进程都无法进入临界区
Operating System Concepts
7.22
Silberschatz, Galvin and Gagne 2002
Algorithm 2-1
 Shared variables
 boolean flag[2];
initially flag [0] = flag [1] = false.
 flag [i] = true  Pi enter its critical section
 Process Pi
do {
while (flag[j]) ;
{ flag[i] := true;
critical section}
flag [i] = false;
remainder section
} while (1);
 Satisfies mutual exclusion, but not progress requirement.
 Pi和Pj可能同时进入临界区。当 Pi执行了while (flag[j])后,Pj执行while
(flag[i]) ,这样两个进程同时进入了临界区
Operating System Concepts
7.23
Silberschatz, Galvin and Gagne 2002
7.2.1.3 Algorithm 3
 Combined shared variables of algorithms 1 and 2.
 Process Pi
do {
flag [i]:= true;
turn = j;
while (flag [j] and turn = j) ;
critical section
flag [i] = false;
remainder section
} while (1);
 Meets all three requirements; solves the critical-section
problem for two processes.
Operating System Concepts
7.24
Silberschatz, Galvin and Gagne 2002
Algorithm 3
 结合算法1和算法2,是正确的算法
 turn=j;描述可进入的进程(同时修改标志时)
 在进入区先修改后检查,并检查并发修改的先后:
 检查对方flag,如果不在临界区则自己进入--空闲则入
 否则再检查turn:保存的是较晚的一次赋值,则较晚的进程等
待,较早的进程进入--先到先入,后到等待
Operating System Concepts
7.25
Silberschatz, Galvin and Gagne 2002
7.2.1.3 Algorithm 3
 To prove “Mutual exclusion” property
(That is Pi and Pj can’t be in CS at same time)
 Pi enter CS only if flag[j]==false or turn==i
 turn = 0 or 1, but cannot be both
…
 To prove “Progress” property
 Pi is in while statements only when flag[j]==true and turn==j
 Then if Pj is not ready to enter CS, flag[j]==false

if Pj ready to enter CS, flag[j]==true, but turn=i or j , so Pi
or Pj can enter
 To prove “Bounded-waiting” property
 If Pj exit its CS, flag[j]=false, then Pi can enter its CS
Operating System Concepts
7.26
Silberschatz, Galvin and Gagne 2002
Dekker算法 – 7.4题
var boolean flag[2] ;
int turn;
Pi:do {
flag[i]=true;
while flag[j] {
if turn=j {
flag[i]=false;
while turn=j ;
flag[i]=true;
}
}
Critical Section i
turn=j;
flag[i]=false;
Remainder Section
}while(1);
Operating System Concepts
flag[0]=flag[1]=false;
turn=0/1;
请证明:这个算法是否满足临界区
问题的三个条件
7.27
Silberschatz, Galvin and Gagne 2002
7.2.2 Multiple-Process Solutions
Bakery Algorithm (面包房算法)
Algorithm of solving the Critical section for n processes
 Before entering its critical section, process receives a
number. Holder of the smallest number enters the
critical section.
在进入临界区前,进程接收一个数字,最小数字的持有者进
入临界区
 If processes Pi and Pj receive the same number, if i < j,
then Pi is served first; else Pj is served first.
 The numbering scheme always generates numbers in
increasing order of enumeration; i.e., 1,2,3,3,3,3,4,5...
Operating System Concepts
7.28
Silberschatz, Galvin and Gagne 2002
Bakery Algorithm
 Define the following Notation
order : (a,b) -- (ticket #, process id #)
 (a,b) < (c,d) if a < c or if a = c and b < d
 max (a0,…, an-1) is a number, k
such that k  ai for i = 0, …, n – 1
 Shared data
boolean choosing[n];
int number[n];
Data structures are initialized to false and 0
respectively
Operating System Concepts
7.29
Silberschatz, Galvin and Gagne 2002
Fig 7.5 The structure of process Pi in the Bakery Algorithm
取一个编号(在原有编
号基础上+1)
do {
choosing[i] = true;
number[i] = max(number[0], number[1], …, number [n –
1])+1;
choosing[i] = false;
Pj正在取编号
for (j = 0; j < n; j++) {
while (choosing[ j]) ;
while ((number[ j] != 0) &&((number[ j],j) < (number[i],i))) ;
}
critical section
有j欲进入CS且Pj的编号<Pi ,或者Pi
和Pj同时拿到相同编号但j<i
number[i] = 0;
remainder section
} while (1);
此时Pi拥有最小的number[i]
Operating System Concepts
7.30
Silberschatz, Galvin and Gagne 2002
 实现进程同步的方式
 Critical-section (软件方法)
 Synchronization hardware (硬件方法)
 Semaphores (信号量方法)
Operating System Concepts
7.31
Silberschatz, Galvin and Gagne 2002
7.3 Synchronization Hardware
同步的硬件实现 (硬件方法)
 Hardware features can make the programming task
easier and improve system efficiency.
 Hardware instruction: Test and modify the content of a
word atomically.
boolean TestAndSet(boolean &target) {
boolean rv = target;
target = true;
return rv;
}
Operating System Concepts
7.32
Silberschatz, Galvin and Gagne 2002
Mutual Exclusion with Test-and-Set
 Shared data:
boolean lock = false;
 Process Pi
do {
while (TestAndSet(lock)) ;
critical section
lock = false;
remainder section
}while(1);
 利用TestAndSet实现进程互斥:每个临界资源设置一个公共布尔变量
lock,初值为FALSE
 在进入区利用TS进行检查:有进程在临界区时,重复检查;直到其它
进程退出时,检查通过;
Operating System Concepts
7.33
Silberschatz, Galvin and Gagne 2002
The definition of Swap instruction
 Atomically swap two variables.
void Swap(boolean &a, boolean &b) {
boolean temp = a;
a = b;
b = temp;
}
Operating System Concepts
7.34
Silberschatz, Galvin and Gagne 2002
Mutual Exclusion with Swap
 Shared data (initialized to false):
boolean lock;
/* (a global variable)
 Process Pi
do {
key = true;
/* ( a local variable)
while (key == true)
Swap(lock,key);
critical section
lock = false;
remainder section
} while (1);
 Don’t satisfy the bounded-waiting requirement (when Pi,Pj
execute “key=true” at same time)
Operating System Concepts
7.35
Silberschatz, Galvin and Gagne 2002
Fig 7.10 Bounded-waiting mutual exclusion with TestAndSet
Boolean waiting[n], lock ; global variables, to be initialize to false
Do {
waiting[i] =false 意味着另一个进程从
waiting[i]=true;
CS退出,并将Pi设置为可进入
key= true;
while ( waiting[i] && key ) key=TestAndSet(lock);
waiting[i]=false;
critical section;
Key=false 意味着已经没
有一个进程处于CS
j= (i+1) % n ;
while ((j != i) && !waiting[ j ]) j= (j+1) % n ;
if (j == i) lock = false ;
else waiting[ j ] = false ;
remainder section ;
寻找下一个正在等待进入
CS的进程
已经没有正在等待进入CS
的进程
将Pj选为下一个可进入CS
的进程
}while(1)
Operating System Concepts
7.36
Silberschatz, Galvin and Gagne 2002
Bounded-waiting mutual exclusion with TestAndSet
 This algorithm satisfies all the critical section
requirement .
 To prove that the mutual-exclusion(互斥条件)
requirement
 Pi 可以进入CS只有在 waiting[i]== false 或 key == false时
 只有在执行了 TestAndSet后,key 才可能变为 false;而且只有第
一个执行了 TestAndSet 的进程,才能得到 key== false,其它进
程必须等待
 只有在一个进程离开CS时才会有一个(且最多仅有一个)进程的
waiting[i] 由true变为false
 从而确保满足互斥条件
Operating System Concepts
7.37
Silberschatz, Galvin and Gagne 2002
Bounded-waiting mutual exclusion with TestAndSet
 To prove that the progress (有空让进条件)
requirement (see p.200)
 任何一个已经进入CS的进程在“exit section” 时,设置:lock
=false 或 waiting[ j ]= false,确保了至少可以让一个进程进入CS
 To prove that the bounded-waiting(有限等待条件)
requirement (see p.200)
 任何一个已经进入CS的进程Pi在“exit section” 时, 将会依次扫
描waiting 数组(i+1,i+2,…n-1,0,…i-1),并仅将Pi后面最先找到的
进程j的waiting[ j]设置为false
 这就使进程能依此循环进入CS
Operating System Concepts
7.38
Silberschatz, Galvin and Gagne 2002
 硬件方法的优点
 适用于任意数目的进程,在单处理器或多处理器上
 简单,容易验证其正确性
 可以支持进程内存在多个临界区,只需为每个临界区设立
一个布尔变量
 硬件方法的缺点
 等待要耗费CPU时间,不能实现"让权等待"
 可能"饥饿":从等待进程中随机选择一个进入临界区,有
的进程可能一直选不上
 可能死锁
Operating System Concepts
7.39
Silberschatz, Galvin and Gagne 2002
7.4 Semaphores信号量
--1965年由Dijkstra提出
 软件和硬件方法解决互斥问题的缺陷:
 软件:算法太复杂,效率不高
 中断屏蔽方法:只能用于单机系统
 硬件指令:忙等待
 1965年,荷兰学者Dijkstra提出的信号量机制是一种卓有成
效的进程同步工具。在长期广泛的应用中,信号量机制又得
到了很大的发展,它从整型信号量机制发展到记录型信号量
机制,进而发展为“信号集”机制。现在信号量机制已广泛
应用于OS中。
 Synchronization tool that does not require busy waiting.
一种不需要忙等待的同步工具.
 Semaphore S – integer variable信号量S – 整型变量
 解决N个进程的同步互斥问题
Operating System Concepts
7.40
Silberschatz, Galvin and Gagne 2002
 每个信号量s除一个整数值s.value(计数)外,还有一个进
程等待队列s.L,其中是阻塞在该信号量的各个进程的标识
 信号量只能通过初始化和两个标准的原语来访问--作为
OS核心代码执行,不受进程调度的打断
 初始化指定一个非负整数值,表示空闲资源总数(又称为
"资源信号量")--若为非负值表示当前的空闲资源数,
若为负值其绝对值表示当前等待临界区的进程数
 “二值信号量(binary semaphore)":只允许信号量取0或1值
Operating System Concepts
7.41
Silberschatz, Galvin and Gagne 2002
7.4.1 整型信号量
 Semaphore S – integer variable信号量S – 整型
变量
 can only be accessed via two indivisible
(atomic) operations
仅能通过两个不可分割的[原子]操作访问
wait (S): ( P-操作 )
while S 0 do no-op;
S--;
signal (S): ( V-操作)
S++;
Operating System Concepts
7.42
Silberschatz, Galvin and Gagne 2002
Fig 7.11 Multual-exclusion with semaphores
 Shared data:
semaphore mutex; //initially mutex = 1
 Process Pi:
do {
wait(mutex);
critical section
signal(mutex);
remainder section
} while (1);
Operating System Concepts
7.43
Silberschatz, Galvin and Gagne 2002
7.4.2 记录型信号量
 To overcome the problem of “busy waiting”
 Define a semaphore as a record
typedef struct {
int value;
struct process *L;
} semaphore;
 Assume two simple operations:
 block suspends the process that invokes it.
 wakeup(P) resumes the execution of a blocked
process P.
Operating System Concepts
7.44
Silberschatz, Galvin and Gagne 2002
Implementation
 Semaphore operations now defined as
wait(S) :
S.value--;
if (S.value < 0) {
add this process to S.L;
block;
}
signal(S) :
S.value++;
if (S.value <= 0) {
remove a process P from S.L;
wakeup(P);
}
 value 是负数,表示处于阻塞状态的进程数
Operating System Concepts
7.45
Silberschatz, Galvin and Gagne 2002
wait、signal操作讨论
 信号量的物理含义
S.value >0 表示有S个资源可用;
S.value=0 表示无资源可用或表示不允许进程再进入临
界区;
S.value<0 则|S.value|表示在等待队列中进程的个数
或表示等待进入临界区的进程个数。
wait(S):表示申请一个资源;signal(S)表示释放一个
资源。
Operating System Concepts
7.46
Silberschatz, Galvin and Gagne 2002
wait、signal操作讨论
 wait、signal操作必须成对出现,有一个wait操作就一
定有一个signal操作。当为互斥操作时,它们同处于同
一进程。当为同步操作时,则不在同一进程中出现。
 如果两个wait操作相邻,那么它们的顺序至关重要,而
两个相邻的signal操作的顺序无关紧要。一个同步wait
操作与一个互斥wait操作在一起时,同步wait操作在互
斥wait操作前。
 wait、signal操作的优缺点:
优点:简单,而且表达能力强(用wait、signal操作可
解决任何同步互斥问题。)
缺点:不够安全;wait、signal操作使用不当会出现死
锁;实现复杂。
Operating System Concepts
7.47
Silberschatz, Galvin and Gagne 2002
Semaphore as a General Synchronization Tool
 Execute B in Pj only after A executed in Pi
 Use semaphore flag initialized to 0
 Code:
Pi
…
A
signal(flag)
…
Operating System Concepts
Pj
…
wait(flag)
B
…
7.48
Silberschatz, Galvin and Gagne 2002
同步原语的不可分割性
 含义:
 保证进程间互斥地使用同步原语
 整体操作,不可分割
 实现方法:
 用软件的互斥算法,用开关中断保证整体性
不是好的解决方法
 用硬件开关中断实现互斥和完整性
仅适用于单处理机系统
 用硬件指令方法在多处理机中实现互斥
 用硬件和固件直接实现同步原语
Operating System Concepts
7.49
Silberschatz, Galvin and Gagne 2002
同步原语的不可分割性
 实例: 用硬件指令实现互斥使用的同步原语
Wait(S):
While TS(lock) do skip;
While S<=0 do skip;
S:=S-1;
lock :=false ;
Signal(S):
While TS(lock) do skip;
S:=S+1
lock :=false ;
Operating System Concepts
7.50
/* 上锁
/* 同步原语代码
/* 开锁
/* 上锁
/* 同步原语代码
/* 开锁
Silberschatz, Galvin and Gagne 2002
利用信号量实现:进程互斥
 为使多个进程能互斥地访问某临界资源,只需为该资源设置
一个互斥信号量mutex,并设其初值为1,然后将各进程的临界
区CS置于wait(mutex)和signal(mutex)操作之间即可。利用
信号量实现共享打印机的A、B两进程互斥的类并行PASCAL程
序描述如下:
Operating System Concepts
7.51
Silberschatz, Galvin and Gagne 2002
利用信号量实现进程互斥-1
var mutex:semaphore:=1 ;
begin
parbegin
A:begin
B:begin
Input datd 1 from I/0 1 ; Input datd 2 from I/O 2 ;
Compute……;
Compute……;
wait(mutex) ;
wait(mutex) ;
Print results1 by printer; Print results2 by printer;
signal(mutex) ;
signal(mutex) ;
end
end
parend
end
Operating System Concepts
7.52
Silberschatz, Galvin and Gagne 2002
利用信号量实现:进程同步
 利用信号量能解决进程间的同步问题,这里以下图所示
的计算进程C和打印进程P通过缓冲区Buffer传送数据的
同步问题为例说明。
C
P
Buffer
Operating System Concepts
7.53
Silberschatz, Galvin and Gagne 2002
利用信号量实现进程同步-1
C和P两进程基本算法如下:
C:begin
P: begin
repeat
repeat
Compute next number ;
take from Buffer ;
add to Buffer ;
print last number ;
until false
until false
end
end
 C和P两进程并发执行,必须在执行序列上遵循以下规则,才
能避免错误:
 只有当C进程把数据送入Buffer后,P进程才能从Buffer中取出数据来
打印,否则P进程只能等待。
 只有当P进程从Buffer中取走数据后,C进程才能将新计算的数据再存
入Buffer,否则C进程也只能等待。
Operating System Concepts
7.54
Silberschatz, Galvin and Gagne 2002
利用信号量实现进程同步-2
 为了实现进程同步,需采用同步信号量。
 为了满足第一条同步规则,设置一个同步信号量full,它代表的
资源是缓冲器满,它的初值为0。
 同样为了满足第二条同步规则,设置另一个同步信号量empty,
它代表的资源是缓冲器空,它的初值为1 。
 实现C和P两进程同步的类PASCAL程序:
Operating System Concepts
7.55
Silberschatz, Galvin and Gagne 2002
var: empty,full:semaphore:=1,0 ;
begin
parbegin
C: begin
repeat
Compute next number ;
wait(empty) ;
Add to buffer ;
siganl(full) ;
until false
end
P: begin
repeat
wait(full) ;
Take from Buffer ;
signal(empty) ;
Print last number ;
until false
end
parend
end
Operating System Concepts
7.56
Silberschatz, Galvin and Gagne 2002
7.4.3 Deadlock and Starvation
 Deadlock – two or more processes are waiting
indefinitely for an event that can be caused by only
one of the waiting processes.
死锁 – 两个或多个进程无限期地等待一个事件的发生,而
该事件正是由其中的一个等待进程引起的
 Let S and Q be two semaphores initialized to 1
S和Q是两个初值为1的信号量
P0
P1
wait(S);
wait(Q);
wait(Q);
wait(S);


signal(S);
signal(Q);
signal(Q)
signal(S);
Operating System Concepts
7.57
Silberschatz, Galvin and Gagne 2002
Deadlock and Starvation
 Starvation – indefinite blocking. A process may
never be removed from the semaphore queue in
which it is suspended.
饥饿 – 无限期地阻塞。进程可能永远无法从它等待的信号
量队列中移去
Operating System Concepts
7.58
Silberschatz, Galvin and Gagne 2002
7.4.4 信号量集
 AND型信号量集
 一段处理代码需要同时获取两个或多个临界资源――可
能死锁:各进程分别获得部分临界资源,然后等待其余
的临界资源,“各不相让”
 基本思想:在一个原语中,将一段代码同时需要的多个
临界资源,要么全部分配给它,要么一个都不分配。称
为Swait(Simultaneous Wait)。在Swait时,各个信号
量的次序并不重要,虽然会影响进程归入哪个阻塞队列
,但是由于是对资源全部分配或不分配,所以总有进程
获得全部资源并在推进之后释放资源,因此不会死锁。
Operating System Concepts
7.59
Silberschatz, Galvin and Gagne 2002
AND信号量
Swait(S1, S2, …, Sn)
{while (TRUE)
{ if (S1 >=1 && S2 >= 1 && … && Sn >= 1)
{ for (i = 1; i <= n; ++i) --Si;
break;
}
else
{调用进程进入第一个小于1信号量的等待队列Sj.queue;
阻塞调用进程;
}
}
}
Operating System Concepts
7.60
Silberschatz, Galvin and Gagne 2002
AND信号量
Ssignal(S1, S2, …, Sn)
{ for (i = 1; i <= n; ++i)
{ ++Si;
for (each process P waiting in Si.queue)
{ 从等待队列Si.queue中取出进程P;
if (判断进程P是否通过Swait中的测试)
{
进程P进入就绪队列; }
else
{ 进程P进入某等待队列;}
}
}
}
Operating System Concepts
7.61
Silberschatz, Galvin and Gagne 2002
一般“信号量集”
 一次需要N个某类临界资源时,就要进行N次wait操作--低效又可
能死锁
基本思想:在AND型信号量集的基础上进行扩充:进程对信号量Si
的测试值为ti(用于信号量的判断,即Si >= ti,表示资源数量低于ti
时,便不予分配),占用值为di(用于信号量的增减,即Si = Si - di
和Si = Si + di )
Swait(S1, t1, d1; ...; Sn, tn, dn);
Ssignal(S1, d1; ...; Sn, dn);
一般“信号量集”的几种特定情况:
Swait(S, d, d)表示每次申请d个资源,当少于d个时,便不分配;
Swait(S, 1, 1)表示互斥信号量;
Swait(S, 1, 0)作为一个可控开关(当S1时,允许多个进程进入
临界区;当S=0时,禁止任何进程进入临界区);
一般“信号量集”未必成对使用Swait和Ssignal:如:一起申请
,但不一起释放;
Operating System Concepts
7.62
Silberschatz, Galvin and Gagne 2002
7.4.5 Two Types of Semaphores
 Counting semaphore – integer value can range over
an unrestricted domain.
计数信号量(一般信号量) – 变化范围没有限制的整型值
 Binary semaphore – integer value can range only
between 0 and 1; can be simpler to implement.
二值(二元)信号量 – 变化范围仅限于0和1的信号量;
--容易通过硬件方式实现
Operating System Concepts
7.63
Silberschatz, Galvin and Gagne 2002
Implementing S as a Binary Semaphore
 A counting semaphore S can be implemented using
binary semaphore.
计数信号量S可以用二值信号量实现
 Data structures:
binary-semaphore S1, S2;
int C:
 Initialization:
S1 = 1
S2 = 0
C = initial value of semaphore S
Operating System Concepts
7.64
Silberschatz, Galvin and Gagne 2002
Implementing S
 wait operation
wait(S1);
C--;
if (C < 0) {
signal(S1);
wait(S2);
}
S>0:表示可用资源数目
signal(S1);
S=0:既无可用资源也无进程
等待
 signal operation
S<0:绝对值表示等待的进程
wait(S1);
数
C ++;
if (C <= 0)
signal(S2);
else
signal(S1);
Operating System Concepts
7.65
Silberschatz, Galvin and Gagne 2002
7.5 Classical Problems of Synchronization
经典同步问题
 7.5.1 Bounded-Buffer Problem
有限缓冲区问题(生产者消费者问题)
 7.5.2 Readers and Writers Problem
读者写者问题
 7.5.3 Dining-Philosophers Problem
哲学家就餐问题
Operating System Concepts
7.66
Silberschatz, Galvin and Gagne 2002
7.5.1 Bounded-Buffer Problem
有限缓冲区问题
 (producer-consumer Problem )生产者-消费者问题
 生产者-消费者问题是最著名的同步问题,它描述一组生产
者(P1 ……Pm)向一组消费者(C1……Cq)提供消息。它们
共享一个有界缓冲池(bounded buffer pool),生产者向其
中投放消息,消费者从中取得消息,如下图所示。生产者消费者问题是许多相互合作进程的一种抽象。
Operating System Concepts
7.67
Silberschatz, Galvin and Gagne 2002
P1
Pm
C1
Cq
m
B0
B1
…. …... ………
Bn-1
假定缓冲池中有n个缓冲区,每个缓冲区存放一个消息。由于缓冲池
是临界资源,它只允许一个生产者投入消息,或者一个消费者从中取出
消息。即生产者之间、生产者与消费者之间、消费者之间都必须互斥使
用缓冲池。所以必须设置互斥信号量mutex,它代表缓冲池资源,它的数
值为1。
Operating System Concepts
7.68
Silberschatz, Galvin and Gagne 2002
生产者和消费者二类进程P和C之间应满足下列二个同步条件:
 只有在缓冲池中至少有一个缓冲区已存入消息后,消费者才
能从中提取消息,否则消费者必须等待。
 只有缓冲池中至少有一个缓冲区是空时,生产者才能把消息
放入缓冲区,否则生产者必须等待。
为了满足第一个同步条件,设置一个同步信号量full,它代
表的资源是缓冲区满,它的初始值为0,它的值为n时整个缓
冲池满。同样为了满足第二个同步条件,设置另一个同步信
号量empty,它代表的资源是缓冲区空,它的初始值为n,表
示缓冲池中所有缓冲区空。
Operating System Concepts
7.69
Silberschatz, Galvin and Gagne 2002
Bounded-Buffer Problem
有限缓冲区问题
 Shared data
Semaphore: full, empty, mutex;
full
– 满缓冲器的数量
empty – 空缓冲器的数量
mutex – 对缓冲器操作的互斥变量
Initially:
full = 0, empty = n, mutex = 1
Operating System Concepts
7.70
Silberschatz, Galvin and Gagne 2002
Fig 7.12 The structure of Producer Process
do {
…
produce an item in nextp
…
…
add nextp to buffer
…
} while (1);
Operating System Concepts
7.71
Silberschatz, Galvin and Gagne 2002
Fig 7.13 structure of the Consumer Process
do {
…
remove an item from buffer to nextc
…
…
consume the item in nextc
…
} while (1);
Operating System Concepts
7.72
Silberschatz, Galvin and Gagne 2002
Fig 7.12 The structure of Producer Process
do {
…
produce an item in nextp
…
wait(mutex);
…
add nextp to buffer
…
signal(mutex);
} while (1);
Operating System Concepts
7.73
Silberschatz, Galvin and Gagne 2002
Fig 7.13 structure of the Consumer Process
do {
wait(mutex);
…
remove an item from buffer to nextc
…
signal(mutex);
…
consume the item in nextc
…
} while (1);
Operating System Concepts
7.74
Silberschatz, Galvin and Gagne 2002
Fig 7.12 The structure of Producer Process
do {
…
produce an item in nextp
…
wait(empty);
wait(mutex);
…
add nextp to buffer
…
signal(mutex);
signal(full);
} while (1);
Operating System Concepts
7.75
Silberschatz, Galvin and Gagne 2002
Fig 7.13 structure of the Consumer Process
do {
wait(full);
wait(mutex);
…
remove an item from buffer to nextc
…
signal(mutex);
signal(empty);
…
consume the item in nextc
…
} while (1);
Operating System Concepts
7.76
Silberschatz, Galvin and Gagne 2002
7.5.2 The Readers-Writers Problem
读者写者问题
 一个数据集(如文件)如果被几个并行进程所共享,
有些进程只要求读数据集内容,它称读者(Reader),
而另一些进程则要求修改数据集内容,它称写者
(Writer),几个读者可以同时读些数据集,而不需要
互斥,但一个写者不能和其它进程(不管是写者或读
者)同时访问些数据集,它们之间必须互斥。
 Shared data
semaphore mutex, wrt;
Initially
mutex = 1, wrt = 1, readcount = 0
Operating System Concepts
7.77
Silberschatz, Galvin and Gagne 2002
Fig 7.14 The structure of a Writer Process
引人互斥信号量 wrt
wait(wrt);
…
writing is performed
…
signal(wrt);
Operating System Concepts
7.78
Silberschatz, Galvin and Gagne 2002
Fig 7.15 The structure of a Reader Process
第一个读者到时:
wait(wrt);
…
reading is performed
…
最后一个读者离开时:
signal(wrt);
Operating System Concepts
7.79
Silberschatz, Galvin and Gagne 2002
Fig 7.15 The structure of a Reader Process
 用readcount变量来记录读者数,读者程序为:
readcount++;
if (readcount == 1)
wait(wrt);
…
reading is performed
…
readcount--;
if (readcount == 0)
signal(wrt);
Operating System Concepts
7.80
Silberschatz, Galvin and Gagne 2002
Fig 7.15 The structure of a Reader Process
 由于readcount是读者间共享变量,属于临界资源,它也需互斥,为此又
引人互斥信号量mutex:
wait(mutex);
/*确保互斥访问
readcount++;
if (readcount == 1) /*第一个读者进入时
wait(wrt); 确保没有写者存在
signal(mutex);
…
reading is performed
…
wait(mutex);
/*确保互斥访问
readcount--;
if (readcount == 0)
/*最后一个读者离开时
signal(wrt);
唤醒可能等待的写者
signal(mutex);
Operating System Concepts
7.81
Silberschatz, Galvin and Gagne 2002
用一般信号集机制解读者-写者问题
 采用一般"信号量集"机制:增加一个限制条件:同时读的"读者"最
多RN个
 mx表示"允许写",初值是1
 L表示"允许读者数目",初值为RN
var RN integer ;
L , mx : semaphore :=RN ,1 ;
begin
parbegin
reader : begin
repeat
Swait (L , 1 , 1 ) ;
Swait (mx , 1 , 0 ) ;
perform read operation
Ssignal (L , 1) ;
until false ;
end
Operating System Concepts
7.82
Silberschatz, Galvin and Gagne 2002
用一般信号集机制解读者-写者问题-1
writer: begin
repeat
Swait (mx ,1, 1, L , RN , 0 );
perform write operation
Ssignal (mx , 1 ) ;
until false ;
end
parend
end
Operating System Concepts
7.83
Silberschatz, Galvin and Gagne 2002
7.5.3 Dining-Philosophers Problem
哲学家就餐问题
 问题描述:(由Dijkstra首先提出并解决)
 5个哲学家围绕一张圆桌而坐,桌子上放着5支
筷子,每两个哲学家之间放一支;
 哲学家的动作包括思考和进餐;
 进餐时需要同时拿起他左边和右边的两支筷子
;思考时则同时将两支筷子放回原处。
 如何保证哲学家们的动作有序进行?如:不出
现相邻者同时要求进餐;不出现有人永远拿不
到筷子;
Operating System Concepts
7.84
Silberschatz, Galvin and Gagne 2002
Dining-Philosophers Problem
 Shared data
semaphore chopstick[5];
Initially all values are 1
Operating System Concepts
7.85
Silberschatz, Galvin and Gagne 2002
Fig 7.17 The structure of Philosophers i
 Philosopher i:
do {
wait(chopstick[i])
wait(chopstick[(i+1) % 5])
…
eat
…
signal(chopstick[i]);
signal(chopstick[(i+1) % 5]);
…
think
…
} while (1);
Operating System Concepts
7.86
Silberschatz, Galvin and Gagne 2002
哲学家就餐问题讨论
为防止死锁发生可采取的措施:
 最多允许4个哲学家同时坐在桌子周围
 仅当一个哲学家左右两边的筷子都可用时,才允许他
拿筷子
 给所有哲学家编号,奇数号的哲学家必须首先拿左边
的筷子,偶数号的哲学家则反之
 为了避免死锁,把哲学家分为三种状态,思考,饥饿
,进食,并且一次拿到两只筷子,否则不拿
Operating System Concepts
7.87
Silberschatz, Galvin and Gagne 2002
7.6 Critical Regions
临界区
 信号量存在的问题
 Signal和Wait 使用次序颠倒
signal(mutex)
…
critical section
…
wait(mutex)
当多个进程同时访问临界区时,破坏了临界资源的互斥
性
Operating System Concepts
7.88
Silberschatz, Galvin and Gagne 2002
Critical Regions
 信号量存在的问题-1
 Wait 被换成Signal
wait(mutex)
…
critical section
…
wait(mutex)
Result: Deadlock will occur
Operating System Concepts
7.89
Silberschatz, Galvin and Gagne 2002
Critical Regions
 信号量存在的问题-2
 缺少Wait或Signal
 Result: 破坏互斥性或造成死锁
Operating System Concepts
7.90
Silberschatz, Galvin and Gagne 2002
Critical Regions
 High-level synchronization construct
 A shared variable v of type T, is declared as:
v: shared T
 Variable v accessed only inside a region
statement
region v when B do S
where B is a boolean expression.
 It means “while statement S is being executed,
no other process can access variable v. ”
Operating System Concepts
7.91
Silberschatz, Galvin and Gagne 2002
(conditional) Critical Regions
 Regions referring to the same shared variable
exclude each other in time.
访问区域相同共享变量同时互斥。
 When a process tries to execute the region
statement, the Boolean expression B is evaluated.
If B is true, statement S is executed. If it is false,
the process is delayed until B becomes true and
no other process is in the region associated with
v.
Operating System Concepts
7.92
Silberschatz, Galvin and Gagne 2002
(conditional) Critical Regions
 If two statements are executed concurrently
in two processes:
region v when (true) S1
region v when (true) S2
The result will be executed sequentially as
“S1 followed by S2” or “S2 followed by
S1”
Operating System Concepts
7.93
Silberschatz, Galvin and Gagne 2002
Example – Bounded Buffer
 Critical-region construct 可以有效地解决一般
的同步问题。
 例如:生产者-消费者问题:
 Shared data:
struct buffer {
int pool[n];
int count, in, out;
}
Operating System Concepts
7.94
Silberschatz, Galvin and Gagne 2002
Bounded Buffer Producer Process
 Producer process inserts nextp into the shared
buffer
region buffer when( count < n) {
pool[in] = nextp;
in:= (in+1) % n;
count++;
}
Operating System Concepts
7.95
Silberschatz, Galvin and Gagne 2002
Bounded Buffer Consumer Process
 Consumer process removes an item from the shared
buffer and puts it in nextc
region buffer when (count > 0) {
nextc = pool[out];
out = (out+1) % n;
count--;
}
Operating System Concepts
7.96
Silberschatz, Galvin and Gagne 2002
Implementation region x when B do S
(自学)
 The conditional critical region could be implemented
by a compiler.
 Associate with the shared variable x, the following
variables:
semaphore mutex, first-delay, second-delay;
int first-count, second-count;
 Mutually exclusive access to the critical section is
provided by mutex.
mutex提供互斥访问临界区。
 If a process cannot enter the critical section because
the Boolean expression B is false, it initially waits on
the first-delay semaphore; moved to the second-delay
semaphore before it is allowed to reevaluate B.
如果因为布尔表达式 B 是false,进程不能进入临界区,它
开始等待first-delay信号量;在它被允许再计算B以前,改
到second-delay信号量。7.97
Operating System Concepts
Silberschatz, Galvin and Gagne 2002
Implementation region x when B do S (Cont.)
wait(mutex);
while(!B) {
first_count++;
if (second_count>0) signal(second_delay);
else signal(mutex);
wait(first_delay);
first_count--;
second_count++;
if (first_count>0) signal(first_delay);
else signal(second_delay);
wait(second_delay);
second_count--;
}
S;
Operating System Concepts
7.98
Silberschatz, Galvin and Gagne 2002
Implementation region x when B do S (Cont.)
If (first_count>0) signal(first_delay);
else if (second_count>0) signal(second_delay);
else signal(mutex);
Operating System Concepts
7.99
Silberschatz, Galvin and Gagne 2002
Implementation
 Keep track of the number of processes waiting on
first-delay and second-delay, with first-count and
second-count respectively.
记录等待first-delay and second-delay的进程数
与first-count and second-count分别地。
 The algorithm assumes a FIFO ordering in the
queuing of processes for a semaphore.
算法假定信号量进程队列为一个FIFO
 For an arbitrary queuing discipline, a more
complicated implementation is required.
为任意队列要求,需要更复杂的实现
Operating System Concepts
7.100
Silberschatz, Galvin and Gagne 2002
7.7 Monitors管程
用信号量可实现进程间的同步,但由于信号量的
控制分布在整个程序中,其正确性分析很困难。
管程是管理进程间同步的机制,它保证进程互斥
地访问共享变量,并方便地阻塞和唤醒进程。
管程可以函数库的形式实现。相比之下,管程比
信号量好控制。
Operating System Concepts
7.101
Silberschatz, Galvin and Gagne 2002
1. 信号量同步的缺点
 同步操作分散:信号量机制中,同步操作分散在各个
进程中,使用不当就可能导致各进程死锁(如wait、
signal操作的次序错误、重复或遗漏)
 易读性差:要了解对于一组共享变量及信号量的操作
是否正确,必须通读整个系统或者并发程序;
 不利于修改和维护:各模块的独立性差,任一组变量
或一段代码的修改都可能影响全局;
 正确性难以保证:操作系统或并发程序通常很大,很
难保证这样一个复杂的系统没有逻辑错误;
Operating System Concepts
7.102
Silberschatz, Galvin and Gagne 2002
2. 管程的引入
 最早由Dijkstra提出, 1974年,Hoare和Hanson所实现;其
基本思想是把信号量及其操作原语封装在一个对象内部。即
:将共享变量以及对共享变量能够进行的所有操作集中在一
个模块中。
 管程的定义:管程是关于共享资源的数据结构及一组针对该
资源的操作过程所构成的软件模块。
 管程可增强模块的独立性:系统按资源管理的观点分解成若
干模块,用数据表示抽象系统资源,同时分析了共享资源和
专用资源在管理上的差别,按不同的管理方式定义模块的类
型和结构,使同步操作相对集中,从而增加了模块的相对独
立性
 引入管程可提高代码的可读性,便于修改和维护,正确性易
于保证:采用集中式同步机制。一个操作系统或并发程序由
若干个这样的模块所构成,一个模块通常较短,模块之间关
系清晰。
Operating System Concepts
7.103
Silberschatz, Galvin and Gagne 2002
 High-level synchronization construct that allows the
safe sharing of an abstract data type among
concurrent processes.
高级的同步机构允许并发进程间一种抽象的数据类型安全
共享。
 A monitor is characterized by a set of programmingdefined operators
一个管程表示一个编程定义操作的集合
 The monitor construct ensures that only one process
at a time can be active within monitor.
管程结构保证在某一时刻仅仅一个进程运行在管程里。
Operating System Concepts
7.104
Silberschatz, Galvin and Gagne 2002
3. 管程的主要特性
 模块化:一个管程是一个基本程序单位,可以单独编译;
 抽象数据类型:管程是一种特殊的数据类型,其中不仅有
数据,而且有对数据进行操作的代码
 信息封装:管程是半透明的,管程中的外部过程(函数)
实现了某些功能,至于这些功能是怎样实现的,在其外部
则是不可见的;
Operating System Concepts
7.105
Silberschatz, Galvin and Gagne 2002
4. 管程的实现要素
 管程中的共享变量在管程外部是不可见的,外部只能
通过调用管程中所说明的外部过程(函数)来间接地
访问管程中的共享变量;
 为了保证管程共享变量的数据完整性,规定管程互斥
进入;
 管程通常是用来管理资源的,因而在管程中应当设有
进程等待队列以及相应的等待及唤醒操作;
Operating System Concepts
7.106
Silberschatz, Galvin and Gagne 2002
5. 管程中的多个进程进入
 当一个进入管程的进程执行等待操作时,它应当释放管程的
互斥权;当一个进入管程的进程执行唤醒操作时(如P唤醒
Q),管程中便存在两个同时处于活动状态的进程。
 管程中的唤醒切换方法:
 P等待Q继续,直到Q等待或退出;
 Q等待P继续,直到P等待或退出;
 规定唤醒为管程中最后一个可执行的操作;
Operating System Concepts
7.107
Silberschatz, Galvin and Gagne 2002
 入口等待队列:因为管程是互斥进入的,所以当一个进程试
图进入一个巳被占用的管程时它应当在管程的入口处等待,
因而在管程的入口处应当有一个进程等待队列,称作入口等
待队列。
 紧急等待队列:如果进程P唤醒进程Q,则P等待Q继续,
如果进程Q在执行又唤醒进程R,则Q等待R继续,...,如
此,在管程内部,由于执行唤醒操作,可能会出现多个等待
进程(已被唤醒,但由于管程的互斥进入而等待),因而还
需要有一个进程等待队列,这个等待队列被称为紧急等待队
列。它的优先级应当高于入口等待队列的优先级。
Operating System Concepts
7.108
Silberschatz, Galvin and Gagne 2002
6. 条件变量(condition)
 由于管程通常是用于管理资源的,因而在管程内部,
应当存在某种等待机制。当进入管程的进程因资源被
占用等原因不能继续运行时使其等待。为此在管程内
部可以说明和使用一种特殊类型的变量----条件变量。
每个表示一种等待原因,并不取具体数值--相当于
每个原因对应一个队列。
Operating System Concepts
7.109
Silberschatz, Galvin and Gagne 2002
Fig 7.21 Monitor With Condition Variables
Operating System Concepts
7.110
Silberschatz, Galvin and Gagne 2002
 同步操作原语wait和signal:针对条件变量x,x.wait()将自己阻
塞在x队列中,x.signal()将x队列中的一个进程唤醒。
 x.wait():如果紧急等待队列非空,则唤醒第一个等待者;否则释
放管程的互斥权,执行此操作的进程排入x队列尾部(紧急等待队
列与x队列的关系:紧急等待队列是由于管程的互斥进入而等待的
队列,而x队列是因资源被占用而等待的队列)
 X.signal():如果x队列为空,则相当于空操作,执行此操作的进
程继续;否则唤醒第一个等待者,执行此操作的进程排入紧急等
待队列的尾部
 若进程P唤醒进程Q,则随后可有两种执行方式(进程P、Q都是管程
中的进程)
 P等待,直到执行Q离开管程或下一次等待。Hoare采用。
 Q送入Ready队列,直到执行P离开管程或下一次等待。1980年,
Lampson和Redell采用。
Operating System Concepts
7.111
Silberschatz, Galvin and Gagne 2002
7. 管程的的组成
 名称:为每个共享资源设立一个管程
 数据结构说明:一组局部于管程的控制变量
 操作原语:对控制变量和临界资源进行操作的一组原语过程(程序代码
),是访问该管程的唯一途径。这些原语本身是互斥的,任一时刻只允
许一个进程去调用,其余需要访问的进程就等待。
 初始化代码:对控制变量进行初始化的代码
Operating System Concepts
7.112
Silberschatz, Galvin and Gagne 2002
The syntax of a monitor管程的语法

monitor monitor-name
{
shared variable declarations
procedure body P1 (…) { . . .
}
procedure body P2 (…) { . . .
}
procedure body Pn (…) {
...
}
{
initialization code
}
}
Operating System Concepts
7.113
Silberschatz, Galvin and Gagne 2002
Fig 7.20 Schematic View of a Monitor
Operating System Concepts
7.114
Silberschatz, Galvin and Gagne 2002
8. 管程和进程的异同点
 设置进程和管程的目的不同
 系统管理数据结构
 进程:PCB
 管程:等待队列
 管程被进程调用
 管程是操作系统的固有成分,无创建和撤消
Operating System Concepts
7.115
Silberschatz, Galvin and Gagne 2002
Monitors (Cont.-1)
 To allow a process to wait within the monitor, a
condition variable must be declared, as
允许一个进程在管程里等待(阻塞),一个条件变量必须
被声明
condition x, y;
 Condition variable can only be used with the
operations wait and signal.
条件变量只能使用wait 和 signal 操作
Operating System Concepts
7.116
Silberschatz, Galvin and Gagne 2002
Monitors (Cont.-2)
 The operation x.wait()
means that the process invoking this operation is
suspended until another process invokes
x.signal();
x.wait ()操作表示调用这操作的进程挂起在条件x上,
直到另外的进程调用 x.signal ()
 The x.signal operation resumes exactly one
suspended process. If no process is suspended,
then the signal operation has no effect.
x.signal()操作恢复(唤醒)在条件x上被挂起进程。如
果没有进程被挂起,那么signal操作没有效果。[注意:
与信号量的区别]
Operating System Concepts
7.117
Silberschatz, Galvin and Gagne 2002
Fig 7.20 Schematic View of a Monitor
Operating System Concepts
7.118
Silberschatz, Galvin and Gagne 2002
Fig 7.21 Monitor With Condition Variables
Operating System Concepts
7.119
Silberschatz, Galvin and Gagne 2002
Structure of Monitor
Monitior Waiting Area
Queue of
Entering
Processes
Entrance
M0NITOR
Local Data
Condition c1
Condition Variables
C1.wait
.
.
.
Procedure 1
.
.
.
condition cn
Procedure k
Cn.wait
Urgent Queue
Initialization Code
Cx.signal
Operating System Concepts
Exit
7.120
Silberschatz, Galvin and Gagne 2002
Monitors (Cont.-2)
 When the x.signal() operation is invoked by process P,
there is a suspended process Q associated with
condition X. Two possibilities exist:
当 x.signal () 操作被进程 P 调用, 有一个与条件便变量 X相
关的被挂进程Q 。存在二个可能性:
1. P either waits until Q leaves the monitor, or waits for
another condition.
P等待直到 Q 离开管程,或等另外的条件。
2. Q either waits until P leaves the monitor, or waits for
another condition.
Q等待直到 P 离开管程,或等另外的条件。
Operating System Concepts
7.121
Silberschatz, Galvin and Gagne 2002
Example of Monitor
 A monitor solution to the Dining- Philosophers
Operating System Concepts
7.122
Silberschatz, Galvin and Gagne 2002
Fig 7.22 A monitor solution to the Dining- Philosophers
monitor dp
{
enum {thinking, hungry, eating} state[5];
//每个哲学家都处在“thinking, hungry, eating”三种状态之一
condition self[5];
void pickup(int i)
// following slides
void putdown(int i) // following slides
void test(int i)
// following slides
void init() {
for (int i = 0; i < 5; i++)
state[i] = thinking;
}
}
Operating System Concepts
7.123
Silberschatz, Galvin and Gagne 2002
Fig 7.22 A monitor solution to the DiningPhilosophers (Cont.)
void pickup(int i) {
state[i] = hungry;
test[i];
if (state[i] != eating)
self[i].wait();
}
void putdown(int i) {
state[i] = thinking;
// test left and right neighbors
test((i+4) % 5); //唤醒可能在self[i+4]上阻塞的进程
test((i+1) % 5); //唤醒可能在self[i+1]上阻塞的进程
}
Operating System Concepts
7.124
Silberschatz, Galvin and Gagne 2002
Fig 7.22 A monitor solution to the DiningPhilosophers (Cont.-1)
void test(int i) {
if ( (state[(i + 4) % 5] != eating) &&
(state[i] == hungry) &&
(state[(i + 1) % 5] != eating)) {
state[i] = eating;
self[i].signal();
}
}
Operating System Concepts
7.125
Silberschatz, Galvin and Gagne 2002
Fig 7.22 A monitor solution to the DiningPhilosophers (Cont.-2)
 Philosopher[i]:
Do{ dp.pickup(i);
eat
dp.putdown(i);
think
}while(1)
 确保:
 No deadlock will occur
 It’s possible for a philosopher to starve to
death
Operating System Concepts
7.126
Silberschatz, Galvin and Gagne 2002
Monitor Implementation Using Semaphores[*]
 Variables
semaphore mutex; // (initially = 1)
semaphore next; // (initially = 0)
int next-count = 0;
 Each external procedure F will be replaced by
wait(mutex);
…
body of F;
…
if (next-count > 0)
signal(next)
else
signal(mutex);
 Mutual exclusion within a monitor is ensured.
Operating System Concepts
7.127
Silberschatz, Galvin and Gagne 2002
Monitor Implementation [*]
 For each condition variable x, we have:
semaphore x-sem; // (initially = 0)
int x-count = 0;
 The operation x.wait can be implemented as:
x-count++;
if (next-count > 0)
signal(next);
else
signal(mutex);
wait(x-sem);
x-count--;
Operating System Concepts
7.128
Silberschatz, Galvin and Gagne 2002
Monitor Implementation
 The operation x.signal can be implemented as:
if (x-count > 0) {
next-count++;
signal(x-sem);
wait(next);
next-count--;
}
Operating System Concepts
7.129
Silberschatz, Galvin and Gagne 2002
Monitor Implementation
 Conditional-wait construct: x.wait(c);
 c – integer expression that is evaluated when the
wait operation is executed.
 value of c (a priority number) stored with the name
of the process that is suspended.
 when x.signal is executed, process with smallest
associated priority number is resumed next.
Operating System Concepts
7.130
Silberschatz, Galvin and Gagne 2002
Monitor Implementation(cont.)
 Check two conditions to establish correctness of
system:系统建立正确性要检查 2 个条件:
 User processes must always make their calls on
the monitor in a correct sequence.
用户进程必须正确的顺序调用管程。
 Must ensure that an uncooperative process does
not ignore the mutual-exclusion gateway provided
by the monitor, and try to access the shared
resource directly, without using the access
protocols.
必须保证不同步进程不忽略管程提供了的互斥网关,
并且试图直接存取共享资源, 没有使用存取协议。
Operating System Concepts
7.131
Silberschatz, Galvin and Gagne 2002
7.8 OS Synchronization
操作系统的同步机制
7.8.1 Synchronization in Solaris 2
 Implements a variety of locks to support multitasking,
multithreading (including real-time threads), and multiprocessing.
实现各种锁支持多任务、多线程(包括实时线程)、和多进程
 Uses adaptive mutexes for efficiency when protecting data from
short code segments.
当保护数据短代码段时,为了效率使用可变互斥量
 Uses condition variables and readers-writers locks when longer
sections of code need access to data.
当代码的更长部分需要访问到数据时,使用条件变量和读者-写者锁
 Uses turnstiles to order the list of threads waiting to acquire either
an adaptive mutex or reader-writer lock.
使用 turnstiles(十字转门,栅门) 排列等待需要适应互斥或读者-写者锁的
线程列表
Operating System Concepts
7.132
Silberschatz, Galvin and Gagne 2002
7.8.2 Windows 2000 Synchronization
 Uses interrupt masks to protect access to global
resources on uniprocessor systems.
在单处理机系统上使用中断屏蔽保护存取全局资源
 Uses spinlocks(自旋锁) on multiprocessor systems.
在多处理机系统上使用自旋锁。
 利用busy waiting 而非blocking来阻止进程前进;
 CPU不会去做其他事情,虽然浪费了部分CPU时间,但省去了进程切换;
 适合短代码的加锁:
wait(S):
S--;
while S<0 do{};
signal(S):
S++;
 与spin lock相对应的就是suspend lock(挂起锁),即一般的锁,会挂起
(阻塞)进程的执行
Operating System Concepts
7.133
Silberschatz, Galvin and Gagne 2002
Windows 2000 Synchronization (cont.)
 Provides dispatcher objects for thread synchronization
outside of the kernel .
为内核外线程同步提供调度器对象 。
 Using a dispatcher objects, a thread can synchronize
according to several different mechanisms include
mutexes 、semaphores and event. An event acts much
like a condition variable.
使用一个调度器对象, 一个线程能根据不同的同步机制,包括
互斥 、信号量和事件等。一个事件类似一个条件变量。
 Dispatcher objects may be in either a signaled or
nonsignaled state.
调度器对象可以在任何一个signaled可用或 nonsignaled不
可用状态。
Operating System Concepts
7.134
Silberschatz, Galvin and Gagne 2002
Windows 2000/XP的进程互斥和同步
在Windows 2000/XP中提供了互斥对象、信号量对象和事件
对象等三种同步对象和相应的系统调用,用于进程和线程同
步。从本质上讲,这组同步对象的功能是相同的,它们的区
别在于适用场合和效率会有所不同。
对象名称是由用户给出的字符串。不同进程中用同样的名
称来创建或打开对象,从而获得该对象在本进程的句柄。
对象状态可分成可用和不可用两种。对象可用(signaled
state)表示该对象不被任何线程使用或所有;而对象不可用
(nonsignaled state)表示该对象被某线程使用。
返回
Operating System Concepts
7.135
Silberschatz, Galvin and Gagne 2002
Windows 2000/XP的进程互斥和同步-1
 互斥对象(Mutex)相当于互斥信号量,在一个时刻只能被一




个线程使用。
信号量对象(Semaphore)是资源信号量,它的取值在0到指定
最大值之间,用于限制并发访问的线程数。
事件对象(Event)相当于“触发器”,可通知一个或多个线
程某事件的出现。
临界区对象(Critical Section)只能用于在同一进程内使用
的临界区,同一进程内各线程对它的访问是互斥进行的。
互锁变量访问是最基本的互斥手段,其他的互斥和共享机制
都是以它为基础的。它相当于硬件TS指令。用于对整型变量
的操作,可避免线程间切换对操作连续性的影响。
Operating System Concepts
7.136
Silberschatz, Galvin and Gagne 2002
7.9 Atomic Transactions[*]
原子事务处理
To use database-systems techniques in operating system
7.9.1 System Model 系统模型
 A collection of instructions (or operations) that
performs a single logical function is called a
transaction(事务).
 A major issue in processing transactions is the
preservation of atomicity(保护原子性) despite the
possibility of failures within the computer system.
 A transaction is simply a sequence of read and write
operation,terminated by either a commit operation or an
abort operation.
 The state of the data accessed by an aborted
transaction must be restored to what it just before the
started executing. Such a transaction has been rolled
back回退.
Operating System Concepts
7.137
Silberschatz, Galvin and Gagne 2002
Atomic Transactions (cont.)
 We are concerned with ensuring transaction atomicity
in an environment where failure result in loss of
information on volatile storage (nonvolatile storage
,stable storage).
7.9.2 Log-Based Recovery 基于日志的恢复
 One way to ensure atomicity is to record , on stable
storage, information describing all the modifications
made by the transactions to the various data it
accessed. The most widely used method for achieving
this form of recording is write-ahead logging (预写日志
纪录) 。
 The system maintains , on stable storage , a data
structure called the log(日志). Each log record
describes a single operation of a transaction write , and
has the following fields: Transaction Name , Data Item
Name , Old Value and New Value.
Operating System Concepts
7.138
Silberschatz, Galvin and Gagne 2002
Atomic Transactions (cont.)
 Using the log , the system can handle any failure that
does not result in the loss of information on nonvolatile
storage. The recovery algorithm uses two procedures:
undo(Ti) and redo(Ti).
7.9.3 Checkpoint 检查点
 To reduce these types of overhead : most of the
transactions need to be redone have already actually
updated the data that the log says they need to modify,
we introduce the concept of checkpoint. During
execution ,the system maintain the write-ahead log and
periodically performs checkpoint.
 7.9.4 Concurrent Atomic Transactions
并行的原子事务处理
Operating System Concepts
7.139
Silberschatz, Galvin and Gagne 2002
Ex. 7.4Dekker算法
7.4 第一个公认的解决两进程(线程)临界区问题
的算法是由Dekker提出的,故称为Dekker算法
。算法如下所示。说明该算法满足临界区问题的
三个必要条件。
共享变量:
int turn, 初值为0;
Boolean flag[2],初值均为false;
Pi(i=0,1)
Operating System Concepts
7.140
Silberschatz, Galvin and Gagne 2002
Ex. 7.4Dekker算法(2)
while(1) {
flag[ i ] = true;
while (flag[j]) {
if (turn==j) {
1.互斥(mutual exclusion)
A) Pi和Pj不可能同时进入CS:
turn==j 和turn==I不会同时满足
flag[ i ] = false;
B)一个进程(如Pi)先进入CS,则flag[ i ]为
true,则Pj无法进入
while ( turn == j );
2.前进(progress)
flag[ i ] = true;
A)Pi申请进入,Pj不想进入,则flag[ i
]==false,Pi顺利进入
}
}
B)Pi和Pj都想进入,则turn==j时Pj进入,
turn==i时Pi进入
CS
3.有限等待(bounded waiting)
turn = j;
Pi离开CS后,置turn=j,flag[ i ]=false,这
时Pj可以进入,如果Pj没有进入,Pi又执行
了falg[ i ]=true,则由于turn==j,所以Pi无
法进入,而Pj可以进入
flag[ i ] = false;
RS
}
Operating System Concepts
7.141
Silberschatz, Galvin and Gagne 2002
Ex. 7.5Eisenberg and McGuire’s algorithm
7.5 第一个公认的n进程临界区问题的解决方法是由
Eisenberg和McGuire提出的。该算法中,n个进程共享下
面的变量:
enum pstate { idle, want_in, in_cs };
pstate flag[n];
int turn;
算法描述如下页
证明该算法满足临界区问题的所有要求。
Operating System Concepts
7.142
Silberschatz, Galvin and Gagne 2002
Ex. 7.5Eisenberg and McGuire’s algorithm(2)
1.互斥(mutual exclusion)
While(1) {
A) 两个进程Px和Py不可能同时进入CS:
while(1) {
turn==x 和turn==y不会同时满足,故Px和Py
的两个if 条件不会都满足
flag[i] = want_in;
j = turn;
if (flag[j]!=idle) j = turn
B)一个进程(如Px)先进入CS,则turn==x,
flag[turn]==in_cs,则其他进程无法进入
else j = (j+1)%n;
2.前进(progress)
while (j !=i) {
}
flag[i] =in_cs; j = 0;
while ((j<n)&&(j ==i || flag[j]!=in_cs)
j ++ ;
if ((j>=n)&&(turn==i||flag[turn]==idle))
break;
A)Px申请进入,其他进程不想进入,则其他进
程flag均为idle,则Px的j>=n成立,if条件成立,
跳出while,进入CS
B)若干进程想进入,如Pturn也想进入,则
Pturn优先进入;否则,编号在turn后的最小号
的想进入的进程进入CS
}
turn = i ;
3.有限等待(bounded waiting)
CS
j = (turn+1)%n;
while(flag[j]==idle) j=(j+1)%n;
turn=j; flag[i]=idle;
} Operating System Concepts
RS
Pi离开CS时,置turn为想进入的进程中大于
turn的最小欲进入之进程号,该进程就进入。
进程Pk不会饿死,最多等待(k-turn)个进程的
CS执行
Silberschatz, Galvin and Gagne 2002
7.143
Ex. 7.8 理发问题
7.8 理发问题:一个理发店内有一张沙发,可以坐n个等待理
发的顾客,理发室内有一张理发椅。当没有顾客时,理发
师就休息;当一个新顾客进来时,如果所有的座位上都有
人,他就离开理发店;如果沙发上有空位,他就坐下;如
果理发师在休息,顾客就唤醒他让他为其理发。试用信号
量来同步理发师和顾客的行为。
Operating System Concepts
7.144
Silberschatz, Galvin and Gagne 2002
Ex. 7.8 理发问题(2)
Semaphore max;
//初始n+1,表示理发店可以容纳总人数
Semaphore chair;
//初始n,空闲的椅子
Semaphore barber; //初始1,表示理发椅空闲
Semaphore finished; //初始0,表示一次理发结束
Semaphore ready;
//初始0,表示客人准备就绪
Customer:
While(1){
wait(max); wait(chair);
wait(barber); signal(chair); signal(ready);
… barbered …
wait(finished); signal(max);
}
Barber:
While(1){
wait(ready);
… barbering…
signal(finished);
signal(barber);
}
Operating System Concepts
7.145
Silberschatz, Galvin and Gagne 2002
Ex. 7.9抽烟问题
7.9抽烟问题:有一个烟草代理和三个抽烟者。抽烟者若要抽
烟,必须具有烟叶、烟纸和火柴。三个抽烟者中,一人缺
烟叶、一人缺烟纸、一人缺火柴。烟草代理会源源不断地
分别供应烟叶、烟纸和火柴,并将他们放在桌上。如果他
放的是烟叶,则缺烟叶的抽烟者拾起烟叶,制作香烟,然
后抽烟;其他类推。试用信号量同步烟草代理和三个抽烟
者。
Operating System Concepts
7.146
Silberschatz, Galvin and Gagne 2002
Ex. 7.9抽烟问题(2)
Semaphore smoker[3];
Semaphore material[3];
Semaphore agent;
Int turn;
//初始0,三个抽烟者
//初始0,三种原料
//初始1,供应商
//初始0,轮到谁
Agent:
While(1){
wait(agent);
signal(smoker[turn]);
signal(material[(turn+1)%3]);
signal(material[(turn+2)%3]);
turn= (turn+1)%3;
}
Operating System Concepts
Smoker-i:
While(1){
wait(smoker[i]);
wait(material[(i+1)%3]);
wait(material[(i+2)%3]);
signal(agent);
7.147
}
Silberschatz, Galvin and Gagne 2002
Ex. 7.11
7.11 写一个管程(monitor)用于实现有限缓冲区的生产者
-消费者问题,要求将有限缓冲区置于管程内。
Operating System Concepts
7.148
Silberschatz, Galvin and Gagne 2002
Ex. 7.11(2)
Producer process:
While(1) {
produce an item;
bounded_buffer.put_item();
}
Monitor bounded_buffer
{
item pool[n];
int count, in, out;
condition full, empty;
void get_item()
{
if (count==0) full.wait();
get_from_buffer();
count--;
empty.signal();
}
void put_item()
{
if (count==n) empty.wait();
put_to_buffer();
count++;
full.signal();
}
void init() { count=in=out=0;}
Consumer process:
While (1) {
bounded_buffer.get_item();
consume the item;
}
}
Operating System Concepts
7.149
Silberschatz, Galvin and Gagne 2002
2003年硕士研究生入学考试试题2
4. 关于临界区问题(critical section problem)的一个算法(假设
只有进程P0和P1可能会进入该临界区)如下(i为0或1),该算
法
。
A、不能保证进程互斥进入临界区,且会出现“饥饿”(
Starvation)
B、不能保证进程互斥进入临界区,但不会出现“饥饿”
C、保证进程互斥进入临界区,但会出现“饥饿”
D、保证进程互斥进入临界区,不会出现“饥饿”
repeat
retry:if (turn
-1 ) turn := i;
if (turn
i ) go to retry;
turn := -1;
Critical Section(临界区)
turn := 0;
remainder Section(其它区域)
until false;


答:A
Operating System Concepts
7.150
Silberschatz, Galvin and Gagne 2002
2000年硕士研究生入学考试试题2 (10分)
下述关于双进程临界区问题的算法(对编号为id的进程)是否正确:
do{
blocked[id]=true;
while(turn !=id)of
{
while(blocked[1-id]);
若此时进程切换,且让对方再次进入临
turn=id;
界区,互斥条件无法满足
}
<编号为id的进程的临界区 CS>
blocked[id]=false;
编号为id的进程的非临界区
} while (true):
其中,布尔型数组blocked[2]初始值为为{false,false},整型turn初始值为0
,id代表进程编号(0或1)。请说明它的正确性,或指出错误所在。
Operating System Concepts
7.151
Silberschatz, Galvin and Gagne 2002
2000年硕士研究生入学考试试题3 (10分)
信号量如果只能取0或1为值,就变成了二元信号量。二元
信号量更容易实现。而且,信号量可以由二元信号量替换。
以下所列函数试图用二元信号量操作waitB()和signalB()替换
信号量wait()、signal():
……
其中,用于互斥的二元信号量mutex初始化为1,用于进程挂
起的二元信号量delay初始化为0。请指出该替换算法的错误
所在。
Operating System Concepts
7.152
Silberschatz, Galvin and Gagne 2002
2000年硕士研究生入学考试试题3 (2)
wait(semaphore s)
{
waitB(mutex);
s = s-1;
if (s<0)
{ signalB(mutex);
waitB(delay);
}
else
signalB(mutex);
}
Operating System Concepts
signal(semaphore s)
{ waitB(mutex);
s= s+1;
if(s<=0)
signalB(delay);
signalB(mutex);
}
1、s = 0 时,p1 calls wait() and p2 calls wait()并都
在执行waitB(delay)前交出CPU
2、p3 and p4 call signal()。此时本应允许p1 and p2
wakeup,但因delay升至1后无法再升,导致p1 or p2
中一个仍在wait(delay)
7.153
Silberschatz, Galvin and Gagne 2002
1997年硕士研究生入学考试试题4
下述流程是解决两进程互斥访问临界区问题的一种方法。试
从“互斥”(mutual exclusion)、"空闲让进"(progress
)、"有限等待"(bounded waiting)三方面讨论它的正确性
。如果它是正确的,则证明之;如果它不正确,请说明理由
。
program attemp;
var c1,c2 :integer;
procedure p1(*第一个进程p1*)
begin
repeat
Remain Section 1;
repeat
c1=1-c2;
until c2<>0
Critical Section;(*临界区*)
C1=1;
Until false
Operating System Concepts
Silberschatz, Galvin and Gagne 2002
7.154
1997年硕士研究生入学考试试题4 (2)
Procedure p2 (*另一个进程p2*)
begin
repeat
Remain Section 2;
Repeat
c2=1-c1;
Until c1<>0
Critical Section ;(*临界区*)
c2=1;
until false
end
begin(*主程序*)
c1=1;
c2=1;
cobegin
p1; p2;(*二进程p1,p2开始*)
coend
end
Operating System Concepts
7.155
Silberschatz, Galvin and Gagne 2002
2005年硕士研究生入学考试试题2
试题2 (10分)试就Mutual Exclusion、 Progress、Bounded Waiting 论
述以下解决双进程临界区问题的算法是错误的:
Process P0:
do {
flag[0] =true;
while (flag[1]);
critical section
flag[0] =false;
remainder section
} while (1);
Process P1:
do {
flag[1] =true;
while (flag[0]);
critical section
flag[1] =false;
remainder section
} while (1);
Operating System Concepts
7.156
Silberschatz, Galvin and Gagne 2002
2005年硕士研究生入学考试试题2 (2)
 答案:
 Mutual Exclusion (3分)
 满足
 Progress
(4分)
 不满足
 反例:当P0对flag[0]赋值,紧接着,马上执行P1对
flag[1]的赋值。于是,P0在while(flag[1])语句中等待
,而P1在while(flag[0])语句等待
 Bounded Waiting (3分)
 不满足
Operating System Concepts
7.157
Silberschatz, Galvin and Gagne 2002
2005年硕士研究生入学考试试题1
试题1 (20分)
设某计算机系统有一块CPU、一台输入设备、一台打印机。现有两个
进程同时进入就绪状态,且进程A先得到CPU运行,进程B后运行
。进程A的运行轨迹为:计算50ms,打印100ms,再计算50ms,打
印100ms,结束。进程B的运行轨迹为:计算50ms,输入数据
80ms,再计算100ms,结束。试画出它们的时序关系图(可以用
Gantt Chart),并说明:
(1)开始运行后,CPU有无空闲等待?若有,在哪段时间内等待?计
算CPU的利用率
(2)进程A运行时有无等待现象? 若有,在什么时候发生等待现象?
(3)进程B运行时有无等待现象? 若有,在什么时候发生等待现象?
Operating System Concepts
7.158
Silberschatz, Galvin and Gagne 2002
Exercises
 4, 8, 11
Operating System Concepts
7.159
Silberschatz, Galvin and Gagne 2002
Download