Chapter 7: Process Synchronization 进程同步

159
Silberschatz, Galvin and Gagne 2002 7.1 Operating System Concepts Chapter 7: Process Synchronization 进进进进 7.1 Background 进进 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 进进进进进进

description

Chapter 7: Process Synchronization 进程同步. 7.1 Background 背景 7.2 The Critical-Section Problem 临界区问题 7.3 Synchronization Hardware 同步的硬件实现 - PowerPoint PPT Presentation

Transcript of Chapter 7: Process Synchronization 进程同步

Page 1: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.1Operating System Concepts

Chapter 7: Process Synchronization进程同步 7.1 Background 背景 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 原子事务处理

Page 2: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.2Operating System Concepts

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.

要保持数据的一致性,就需要一种保证并发进程的正确执行顺序的机制

Page 3: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.3Operating System Concepts

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

Page 4: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.4Operating System Concepts

Bounded-Buffer 有界缓冲区 Shared data

#define BUFFER_SIZE 10typedef struct {

. . .} item;item buffer[BUFFER_SIZE];int in = 0;int out = 0;int counter = 0;

Page 5: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.5Operating System Concepts

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++;

}

Page 6: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.6Operating System Concepts

Bounded-Buffer (Cont.-2) Consumer process

item nextConsumed;

while (1) {while (counter == 0); /* do nothing */nextConsumed = buffer[out];out = (out + 1) % BUFFER_SIZE;counter--;}

Page 7: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.7Operating System Concepts

Bounded Buffer (Cont.-3)

The statements

counter++;counter--;

must be performed atomically.

Atomic operation means an operation that completes in its entirety without interruption.

Page 8: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.8Operating System Concepts

Bounded Buffer (Cont.-4)

The statement “count++” may be implemented in machine language as:

register1 = counterregister1 = register1 + 1counter = register1

The statement “count—” may be implemented as:

register2 = counterregister2 = register2 – 1counter = register2

Page 9: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.9Operating System Concepts

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.交替取决于生产者和消费者进程如何调度

Page 10: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.10Operating System Concepts

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.

Page 11: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.11Operating System Concepts

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.防止竞争条件,并发进程必须被同步

Page 12: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.12Operating System Concepts

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.问题 - 保证当一个进程正在临界区执行时,没有另外的进程进入临界区执行

多个进程共享临界资源时必须互斥使用

Page 13: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.13Operating System Concepts

临界资源

进程间资源访问冲突 共享变量的修改冲突 操作顺序冲突

进程间的制约关系 间接制约:进行竞争--独占分配到的部分或全部共享资源,“互斥” 直接制约:进行协作--等待来自其他进程的信息,“同步”

临界资源 : 一次只允许一个进程使用 ( 访问 ) 的资源。如:硬件打印机、磁带机等,软件的消息缓冲队列、变量、数组、缓冲区等。

硬件或软件(如外设、共享代码段、共享数据结构),多个进程在对其进行访问时(关键是进行写入或修改),必须互斥地进行--有些共享资源可以同时访问,如只读数据

多道程序环境- > 进程之间存在资源共享,进程的运行时间受影响

Page 14: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.14Operating System Concepts

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.

有空让进:临界区虽没有进程执行,但有些进程需要进入临界区,不能无限期地延长下一个要进入临界区进程的等待时间 .

Page 15: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.15Operating System Concepts

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个进程相对执行速率的假定

Page 16: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.16Operating System Concepts

同步机制应遵循的准则 空闲让进。 当无进程进入临界区时,相应的临界资源处于空闲状态,因而允许一个请求进入临界区的进程立即进入自己的临界区。 忙则等待 ( 互斥)。 当已有进程进入自己的临界区时,即相应的临界资源正被访问,因而其它试图进入临界区的进程必须等待,以保证进程互斥地访问临界资源。 有限等待。 对要求访问临界资源的进程,应保证进程能在有限时间进入临界区,以免陷入“饥饿”状态。 让权等待。 当进程不能进入自己的临界区时,应立即释放处理机,以免进程陷入忙等。

Page 17: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.17Operating System Concepts

解释 : 使用临界区的原则 每次只允许一个进程处于它的临界区 (CS) 中 若有多个进程同时想进入 CS,应在有限时间内让其中一个进程进入 CS, 以免阻塞 进程在 CS 内只能逗留有限时间 不应使要进入 CS 的进程无限期地等待在 CS 之外 在 CS 之外的进程不可以阻止其他进程进入 CS 不要预期和假定进程进展的相对速度以及可用的处理器数目 . 因为这是不可预期的 .

Page 18: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.18Operating System Concepts

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.

Page 19: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.19Operating System Concepts

7.2.1 Two-Process SolutionsAlgorithm 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 sectionturn = j;reminder section} while (1);

Satisfies mutual exclusion, but not progress( 不满足有空让进条件 )

Page 20: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.20Operating System Concepts

问题 : 必须轮流使用临界区 如果一个进程失败 , 另一个进程将被永久阻塞

缺点:强制轮流进入临界区,没有考虑进程的实际需要。容易造成资源利用不充分:在 Pi 出让临界区之后, Pj 使用临界区之前, Pi 不可能再次使用临界区;

Page 21: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.21Operating System Concepts

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 sectionflag [i] = false;

remainder section} while (1);

Satisfies mutual exclusion, but not progress requirement (see next page).

Page 22: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.22Operating System Concepts

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 ,这样两个进程都无法进入临界区

Page 23: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.23Operating System Concepts

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]) ,这样两个进程同时进入了临界区

Page 24: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.24Operating System Concepts

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 sectionflag [i] = false;

remainder section} while (1);

Meets all three requirements; solves the critical-section problem for two processes.

Page 25: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.25Operating System Concepts

Algorithm 3

结合算法 1 和算法 2 ,是正确的算法 turn=j;描述可进入的进程(同时修改标志时) 在进入区先修改后检查,并检查并发修改的先后:

检查对方 flag ,如果不在临界区则自己进入--空闲则入 否则再检查 turn :保存的是较晚的一次赋值,则较晚的进程等待,较早的进程进入--先到先入,后到等待

Page 26: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.26Operating System Concepts

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

Page 27: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.27Operating System Concepts

Dekker算法 – 7.4 题var boolean flag[2] ; flag[0]=flag[1]=false; int turn; turn=0/1;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);

Page 28: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.28Operating System Concepts

7.2.2 Multiple-Process Solutions Bakery Algorithm (面包房算法 )

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...

Algorithm of solving the Critical section for n processes

Page 29: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.29Operating System Concepts

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 databoolean choosing[n];int number[n];

Data structures are initialized to false and 0 respectively

Page 30: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.30Operating System Concepts

Fig 7.5 The structure of process Pi in the Bakery Algorithm

do { choosing[i] = true;number[i] = max(number[0], number[1], …, number [n – 1])+1;choosing[i] = false;for (j = 0; j < n; j++) {

while (choosing[ j]) ; while ((number[ j] != 0) &&((number[ j],j) <

(number[i],i))) ; }

critical sectionnumber[i] = 0;

remainder section} while (1);

取一个编号(在原有编号基础上 +1 )

有 j 欲进入 CS且 Pj 的编号 <Pi ,或者 Pi 和 Pj 同时拿到相同编号但 j<i

Pj 正在取编号

此时 Pi 拥有最小的 number[i]

Page 31: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.31Operating System Concepts

实现进程同步的方式 Critical-section ( 软件方法 ) Synchronization hardware ( 硬件方法 ) Semaphores ( 信号量方法)

Page 32: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.32Operating System Concepts

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;

}

Page 33: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.33Operating System Concepts

Mutual Exclusion with Test-and-Set

Shared data: boolean lock = false;

Process Pi

do {while (TestAndSet(lock)) ;critical sectionlock = false;remainder section}while(1);

利用 TestAndSet 实现进程互斥:每个临界资源设置一个公共布尔变量lock ,初值为 FALSE

在进入区利用 TS 进行检查:有进程在临界区时,重复检查;直到其它进程退出时,检查通过;

Page 34: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.34Operating System Concepts

The definition of Swap instruction

Atomically swap two variables.

void Swap(boolean &a, boolean &b) {boolean temp = a;a = b;b = temp;

}

Page 35: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.35Operating System Concepts

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)

Page 36: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.36Operating System Concepts

Fig 7.10 Bounded-waiting mutual exclusion with TestAndSet

Boolean waiting[n], lock ; global variables, to be initialize to falseDo { waiting[i]=true; key= true; while ( waiting[i] && key ) key=TestAndSet(lock); waiting[i]=false;

critical section;

j= (i+1) % n ; while ((j != i) && !waiting[ j ]) j= (j+1) % n ; if (j == i) lock = false ; else waiting[ j ] = false ; remainder section ;

}while(1)

Key=false 意味着已经没有一个进程处于 CS

waiting[i] =false 意味着另一个进程从 CS 退出,并将 Pi 设置为可进入

寻找下一个正在等待进入 CS 的进程已经没有正在等待进入CS 的进程将 Pj 选为下一个可进入CS 的进程

Page 37: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.37Operating System Concepts

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 从而确保满足互斥条件

Page 38: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.38Operating System Concepts

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

Page 39: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.39Operating System Concepts

硬件方法的优点适用于任意数目的进程,在单处理器或多处理器上简单,容易验证其正确性 可以支持进程内存在多个临界区,只需为每个临界区设立一个布尔变量

硬件方法的缺点 等待要耗费 CPU 时间,不能实现 "让权等待 " 可能 "饥饿 ":从等待进程中随机选择一个进入临界区,有的进程可能一直选不上 可能死锁

Page 40: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.40Operating System Concepts

7.4 Semaphores 信号量--1965年由 Dijkstra 提出 软件和硬件方法解决互斥问题的缺陷 :

软件 :算法太复杂 ,效率不高 中断屏蔽方法 : 只能用于单机系统 硬件指令 :忙等待

1965年,荷兰学者 Dijkstra 提出的信号量机制是一种卓有成效的进程同步工具。在长期广泛的应用中,信号量机制又得到了很大的发展,它从整型信号量机制发展到记录型信号量机制,进而发展为“信号集”机制。现在信号量机制已广泛应用于 OS 中。 Synchronization tool that does not require busy waiting.一种不需要忙等待的同步工具 . Semaphore S – integer variable 信号量 S – 整型变量 解决 N 个进程的同步互斥问题

Page 41: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.41Operating System Concepts

每个信号量 s 除一个整数值 s.value (计数)外,还有一个进程等待队列 s.L ,其中是阻塞在该信号量的各个进程的标识 信号量只能通过初始化和两个标准的原语来访问--作为

OS核心代码执行,不受进程调度的打断 初始化指定一个非负整数值,表示空闲资源总数(又称为 "资源信号量 ")--若为非负值表示当前的空闲资源数,若为负值其绝对值表示当前等待临界区的进程数

“二值信号量 (binary semaphore)" :只允许信号量取 0或1 值

Page 42: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.42Operating System Concepts

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++;

Page 43: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.43Operating System Concepts

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);

Page 44: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.44Operating System Concepts

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.

Page 45: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.45Operating System Concepts

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 是负数,表示处于阻塞状态的进程数

Page 46: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.46Operating System Concepts

wait、 signal 操作讨论 信号量的物理含义 S.value >0 表示有 S 个资源可用; S.value=0 表示无资源可用或表示不允许进程再进入临界区; S.value<0 则 |S.value|表示在等待队列中进程的个数或表示等待进入临界区的进程个数。 wait(S) :表示申请一个资源; signal(S)表示释放一个资源。

Page 47: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.47Operating System Concepts

wait、 signal 操作讨论 wait、 signal 操作必须成对出现,有一个 wait 操作就一定有一个 signal 操作。当为互斥操作时,它们同处于同一进程。当为同步操作时,则不在同一进程中出现。 如果两个 wait 操作相邻,那么它们的顺序至关重要,而两个相邻的 signal 操作的顺序无关紧要。一个同步wait 操作与一个互斥 wait 操作在一起时,同步 wait操作在互斥 wait 操作前。

wait、 signal 操作的优缺点 : 优点:简单,而且表达能力强(用 wait、 signal 操作可解决任何同步互斥问题。) 缺点:不够安全;wait、 signal 操作使用不当会出现死锁;实现复杂。

Page 48: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.48Operating System Concepts

Semaphore as a General Synchronization Tool

Execute B in Pj only after A executed in Pi

Use semaphore flag initialized to 0 Code:

Pi Pj

……A wait(flag)

signal(flag) B … …

Page 49: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.49Operating System Concepts

同步原语的不可分割性 含义 :

保证进程间互斥地使用同步原语整体操作 , 不可分割

实现方法 : 用软件的互斥算法 , 用开关中断保证整体性

不是好的解决方法 用硬件开关中断实现互斥和完整性

仅适用于单处理机系统 用硬件指令方法在多处理机中实现互斥 用硬件和固件直接实现同步原语

Page 50: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.50Operating System Concepts

同步原语的不可分割性 实例 : 用硬件指令实现互斥使用的同步原语 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 ; /* 开锁

Page 51: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.51Operating System Concepts

利用信号量实现:进程互斥 为使多个进程能互斥地访问某临界资源,只需为该资源设置一个互斥信号量 mutex, 并设其初值为 1 ,然后将各进程的临界区 CS置于 wait(mutex)和 signal(mutex) 操作之间即可。利用信号量实现共享打印机的 A、 B 两进程互斥的类并行 PASCAL 程序描述如下:

Page 52: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.52Operating System Concepts

利用信号量实现进程互斥 -1var mutex:semaphore:=1 ;beginparbeginA: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 endparendend

Page 53: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.53Operating System Concepts

利用信号量实现:进程同步 利用信号量能解决进程间的同步问题,这里以下图所示的计算进程 C 和打印进程 P 通过缓冲区 Buffer传送数据的同步问题为例说明。

Buffer

C P

Page 54: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.54Operating System Concepts

利用信号量实现进程同步 -1C 和 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 进程也只能等待。

Page 55: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.55Operating System Concepts

利用信号量实现进程同步 -2 为了实现进程同步,需采用同步信号量。

为了满足第一条同步规则,设置一个同步信号量 full ,它代表的资源是缓冲器满,它的初值为 0 。 同样为了满足第二条同步规则,设置另一个同步信号量

empty ,它代表的资源是缓冲器空,它的初值为 1 。 实现 C 和 P 两进程同步的类 PASCAL 程序:

Page 56: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.56Operating System Concepts

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 parendend

Page 57: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.57Operating System Concepts

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);

Page 58: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.58Operating System Concepts

Deadlock and Starvation Starvation – indefinite blocking. A process may

never be removed from the semaphore queue in which it is suspended.

饥饿 – 无限期地阻塞。进程可能永远无法从它等待的信号量队列中移去

Page 59: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.59Operating System Concepts

7.4.4 信号量集 AND型信号量集 一段处理代码需要同时获取两个或多个临界资源――可能死锁:各进程分别获得部分临界资源,然后等待其余的临界资源,“各不相让” 基本思想:在一个原语中,将一段代码同时需要的多个临界资源,要么全部分配给它,要么一个都不分配。称为 Swait(Simultaneous Wait) 。在 Swait 时,各个信号量的次序并不重要,虽然会影响进程归入哪个阻塞队列,但是由于是对资源全部分配或不分配,所以总有进程获得全部资源并在推进之后释放资源,因此不会死锁。

Page 60: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.60Operating System Concepts

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; 阻塞调用进程 ; }}}

Page 61: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.61Operating System Concepts

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进入某等待队列; } } }}

Page 62: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.62Operating System Concepts

一般“信号量集” 一次需要 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) 作为一个可控开关(当 S1 时,允许多个进程进入临界区;当 S=0 时,禁止任何进程进入临界区);         一般“信号量集”未必成对使用 Swait和 Ssignal :如:一起申请,但不一起释放;

Page 63: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.63Operating System Concepts

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 的信号量; --容易通过硬件方式实现

Page 64: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.64Operating System Concepts

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 = 1S2 = 0C = initial value of semaphore S

Page 65: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.65Operating System Concepts

Implementing S wait operation

wait(S1);C--;if (C < 0) {signal(S1);wait(S2);}signal(S1);

signal operationwait(S1);C ++;if (C <= 0)signal(S2);elsesignal(S1);

S>0 :表示可用资源数目S=0 :既无可用资源也无进程等待S<0 :绝对值表示等待的进程数

Page 66: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.66Operating System Concepts

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 哲学家就餐问题

Page 67: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.67Operating System Concepts

7.5.1 Bounded-Buffer Problem有限缓冲区问题 ( producer-consumer Problem )生产者 - 消费者问题 生产者 - 消费者问题是最著名的同步问题,它描述一组生产者( P1 ……Pm )向一组消费者( C1……Cq )提供消息。它们共享一个有界缓冲池( bounded buffer pool) ,生产者向其中投放消息,消费者从中取得消息,如下图所示。生产者 - 消费者问题是许多相互合作进程的一种抽象。

Page 68: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.68Operating System Concepts

假定缓冲池中有 n 个缓冲区,每个缓冲区存放一个消息。由于缓冲池是临界资源,它只允许一个生产者投入消息,或者一个消费者从中取出消息。即生产者之间、生产者与消费者之间、消费者之间都必须互斥使用缓冲池。所以必须设置互斥信号量 mutex ,它代表缓冲池资源,它的数值为 1 。

P1 Pm

m

C1 Cq

B0 B1 …. …... ……… Bn-1

Page 69: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.69Operating System Concepts

生产者和消费者二类进程 P 和 C 之间应满足下列二个同步条件: 只有在缓冲池中至少有一个缓冲区已存入消息后,消费者才能从中提取消息,否则消费者必须等待。 只有缓冲池中至少有一个缓冲区是空时,生产者才能把消息放入缓冲区,否则生产者必须等待。 为了满足第一个同步条件,设置一个同步信号量 full ,它代表的资源是缓冲区满,它的初始值为 0 ,它的值为 n 时整个缓冲池满。同样为了满足第二个同步条件,设置另一个同步信号量 empty ,它代表的资源是缓冲区空,它的初始值为

n ,表示缓冲池中所有缓冲区空。

Page 70: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.70Operating System Concepts

Bounded-Buffer Problem有限缓冲区问题 Shared data

Semaphore: full, empty, mutex; full – 满缓冲器的数量 empty – 空缓冲器的数量

mutex – 对缓冲器操作的互斥变量 Initially:

full = 0, empty = n, mutex = 1

Page 71: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.71Operating System Concepts

Fig 7.12 The structure of Producer Process

do { …

produce an item in nextp …

…add nextp to buffer

} while (1);

Page 72: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.72Operating System Concepts

Fig 7.13 structure of the Consumer Process

do {

…remove an item from buffer to nextc …

…consume the item in nextc …} while (1);

Page 73: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.73Operating System Concepts

Fig 7.12 The structure of Producer Process

do { …

produce an item in nextp …

wait(mutex); …

add nextp to buffer …

signal(mutex);

} while (1);

Page 74: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.74Operating System Concepts

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);

Page 75: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.75Operating System Concepts

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);

Page 76: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.76Operating System Concepts

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);

Page 77: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.77Operating System Concepts

7.5.2 The Readers-Writers Problem读者写者问题 一个数据集(如文件)如果被几个并行进程所共享,有些进程只要求读数据集内容,它称读者 (Reader),而另一些进程则要求修改数据集内容,它称写者

(Writer) ,几个读者可以同时读些数据集,而不需要互斥,但一个写者不能和其它进程(不管是写者或读者)同时访问些数据集,它们之间必须互斥。 Shared data

semaphore mutex, wrt;

Initially

mutex = 1, wrt = 1, readcount = 0

Page 78: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.78Operating System Concepts

Fig 7.14 The structure of a Writer Process引人互斥信号量 wrt wait(wrt);

…writing is performed

…signal(wrt);

Page 79: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.79Operating System Concepts

Fig 7.15 The structure of a Reader Process

第一个读者到时 :wait(wrt); …

reading is performed …

最后一个读者离开时 :signal(wrt);

Page 80: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.80Operating System Concepts

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);

Page 81: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.81Operating System Concepts

由于 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);

Fig 7.15 The structure of a Reader Process

Page 82: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.82Operating System Concepts

用一般信号集机制解读者 -写者问题 采用一般 "信号量集 "机制:增加一个限制条件:同时读的 "读者 "最多 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

Page 83: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.83Operating System Concepts

用一般信号集机制解读者 -写者问题 -1writer: begin repeat Swait (mx ,1, 1, L , RN , 0 ); perform write operation Ssignal (mx , 1 ) ; until false ; end parendend

Page 84: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.84Operating System Concepts

7.5.3 Dining-Philosophers Problem哲学家就餐问题 问题描述:(由Dijkstra首先提出并解决)

5 个哲学家围绕一张圆桌而坐,桌子上放着 5支筷子,每两个哲学家之间放一支;哲学家的动作包括思考和进餐; 进餐时需要同时拿起他左边和右边的两支筷子;思考时则同时将两支筷子放回原处。 如何保证哲学家们的动作有序进行?如:不出现相邻者同时要求进餐;不出现有人永远拿不到筷子;

Page 85: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.85Operating System Concepts

Dining-Philosophers Problem

Shared data semaphore chopstick[5];

Initially all values are 1

Page 86: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.86Operating System Concepts

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);

Page 87: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.87Operating System Concepts

哲学家就餐问题讨论为防止死锁发生可采取的措施: 最多允许 4 个哲学家同时坐在桌子周围 仅当一个哲学家左右两边的筷子都可用时,才允许他拿筷子 给所有哲学家编号,奇数号的哲学家必须首先拿左边的筷子,偶数号的哲学家则反之 为了避免死锁,把哲学家分为三种状态,思考,饥饿,进食,并且一次拿到两只筷子,否则不拿

Page 88: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.88Operating System Concepts

7.6 Critical Regions临界区 信号量存在的问题

Signal和Wait 使用次序颠倒signal(mutex) … critical section

…wait(mutex)

当多个进程同时访问临界区时 ,破坏了临界资源的互斥性

Page 89: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.89Operating System Concepts

Critical Regions

信号量存在的问题 -1 Wait 被换成 Signal

wait(mutex) … critical section

…wait(mutex)

Result: Deadlock will occur

Page 90: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.90Operating System Concepts

Critical Regions

信号量存在的问题 -2 缺少Wait或 Signal Result: 破坏互斥性或造成死锁

Page 91: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.91Operating System Concepts

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

statementregion 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. ”

Page 92: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.92Operating System Concepts

(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.

Page 93: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.93Operating System Concepts

(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”

Page 94: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.94Operating System Concepts

Example – Bounded Buffer

Critical-region construct 可以有效地解决一般的同步问题。 例如:生产者 - 消费者问题:

Shared data:

struct buffer {int pool[n];int count, in, out;

}

Page 95: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.95Operating System Concepts

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++;

}

Page 96: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.96Operating System Concepts

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--;

}

Page 97: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.97Operating System Concepts

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 信号量。

Page 98: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.98Operating System Concepts

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;

Page 99: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.99Operating System Concepts

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);

Page 100: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.100Operating System Concepts

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.为任意队列要求,需要更复杂的实现

Page 101: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.101Operating System Concepts

7.7 Monitors 管程用信号量可实现进程间的同步,但由于信号量的控制分布在整个程序中,其正确性分析很困难。管程是管理进程间同步的机制,它保证进程互斥地访问共享变量,并方便地阻塞和唤醒进程。管程可以函数库的形式实现。相比之下,管程比信号量好控制。

Page 102: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.102Operating System Concepts

1. 信号量同步的缺点 同步操作分散:信号量机制中,同步操作分散在各个进程中,使用不当就可能导致各进程死锁(如

wait、 signal 操作的次序错误、重复或遗漏) 易读性差:要了解对于一组共享变量及信号量的操作是否正确,必须通读整个系统或者并发程序; 不利于修改和维护:各模块的独立性差,任一组变量或一段代码的修改都可能影响全局; 正确性难以保证:操作系统或并发程序通常很大,很难保证这样一个复杂的系统没有逻辑错误;

Page 103: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.103Operating System Concepts

2. 管程的引入 最早由 Dijkstra 提出 , 1974年, Hoare和 Hanson 所实现;其基本思想是把信号量及其操作原语封装在一个对象内部。即:将共享变量以及对共享变量能够进行的所有操作集中在一个模块中。 管程的定义:管程是关于共享资源的数据结构及一组针对该资源的操作过程所构成的软件模块。 管程可增强模块的独立性:系统按资源管理的观点分解成若干模块,用数据表示抽象系统资源,同时分析了共享资源和专用资源在管理上的差别,按不同的管理方式定义模块的类型和结构,使同步操作相对集中,从而增加了模块的相对独立性 引入管程可提高代码的可读性,便于修改和维护,正确性易于保证:采用集中式同步机制。一个操作系统或并发程序由若干个这样的模块所构成,一个模块通常较短,模块之间关系清晰。

Page 104: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.104Operating System Concepts

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 programming-defined operators一个管程表示一个编程定义操作的集合

The monitor construct ensures that only one process at a time can be active within monitor.管程结构保证在某一时刻仅仅一个进程运行在管程里。

Page 105: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.105Operating System Concepts

3. 管程的主要特性 模块化:一个管程是一个基本程序单位,可以单独编译; 抽象数据类型:管程是一种特殊的数据类型,其中不仅有数据,而且有对数据进行操作的代码 信息封装:管程是半透明的,管程中的外部过程(函数)实现了某些功能,至于这些功能是怎样实现的,在其外部则是不可见的;

Page 106: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.106Operating System Concepts

4. 管程的实现要素 管程中的共享变量在管程外部是不可见的,外部只能通过调用管程中所说明的外部过程(函数)来间接地访问管程中的共享变量; 为了保证管程共享变量的数据完整性,规定管程互斥进入; 管程通常是用来管理资源的,因而在管程中应当设有进程等待队列以及相应的等待及唤醒操作;

Page 107: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.107Operating System Concepts

5. 管程中的多个进程进入 当一个进入管程的进程执行等待操作时,它应当释放管程的互斥权;当一个进入管程的进程执行唤醒操作时(如P唤醒Q),管程中便存在两个同时处于活动状态的进程。 管程中的唤醒切换方法:

P等待 Q继续,直到 Q等待或退出;Q等待 P继续,直到 P等待或退出;规定唤醒为管程中最后一个可执行的操作;

Page 108: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.108Operating System Concepts

入口等待队列:因为管程是互斥进入的,所以当一个进程试图进入一个巳被占用的管程时它应当在管程的入口处等待,因而在管程的入口处应当有一个进程等待队列,称作入口等待队列。 紧急等待队列:如果进程P唤醒进程Q,则P等待Q继续,如果进程Q在执行又唤醒进程R,则Q等待R继续, ... ,如此,在管程内部,由于执行唤醒操作,可能会出现多个等待进程(已被唤醒,但由于管程的互斥进入而等待),因而还需要有一个进程等待队列,这个等待队列被称为紧急等待队列。它的优先级应当高于入口等待队列的优先级。

Page 109: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.109Operating System Concepts

6. 条件变量 (condition)

由于管程通常是用于管理资源的,因而在管程内部,应当存在某种等待机制。当进入管程的进程因资源被占用等原因不能继续运行时使其等待。为此在管程内部可以说明和使用一种特殊类型的变量 ---- 条件变量。每个表示一种等待原因,并不取具体数值--相当于每个原因对应一个队列。

Page 110: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.110Operating System Concepts

Fig 7.21 Monitor With Condition Variables

Page 111: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.111Operating System Concepts

同步操作原语 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采用。

Page 112: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.112Operating System Concepts

7. 管程的的组成 名称:为每个共享资源设立一个管程 数据结构说明:一组局部于管程的控制变量 操作原语:对控制变量和临界资源进行操作的一组原语过程(程序代码),是访问该管程的唯一途径。这些原语本身是互斥的,任一时刻只允许一个进程去调用,其余需要访问的进程就等待。 初始化代码:对控制变量进行初始化的代码

Page 113: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.113Operating System Concepts

The syntax of a monitor 管程的语法

monitor monitor-name{

shared variable declarationsprocedure body P1 (…) { . . .

}procedure body P2 (…) { . . .

} procedure body Pn (…) {

. . . } {

initialization code}

}

Page 114: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.114Operating System Concepts

Fig 7.20 Schematic View of a Monitor

Page 115: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.115Operating System Concepts

8. 管程和进程的异同点 设置进程和管程的目的不同 系统管理数据结构

进程: PCB 管程:等待队列

管程被进程调用 管程是操作系统的固有成分,无创建和撤消

Page 116: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.116Operating System Concepts

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 操作

Page 117: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.117Operating System Concepts

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 操作没有效果。 [注意 :与信号量的区别 ]

Page 118: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.118Operating System Concepts

Fig 7.20 Schematic View of a Monitor

Page 119: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.119Operating System Concepts

Fig 7.21 Monitor With Condition Variables

Page 120: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.120Operating System Concepts

Structure of MonitorEntrance

Queue ofEnteringProcessesMonitior Waiting Area

Condition c1

C1.wait

.

.

.

condition cn

.

.

.

Cn.wait

Urgent Queue

Cx.signal Exit

M0NITOR

Local Data

Condition Variables

Procedure 1

Procedure k

Initialization Code

Page 121: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.121Operating System Concepts

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 离开管程,或等另外的条件。

Page 122: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.122Operating System Concepts

Example of Monitor A monitor solution to the Dining- Philosophers

Page 123: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.123Operating System Concepts

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 slidesvoid putdown(int i) // following slidesvoid test(int i) // following slidesvoid init() {for (int i = 0; i < 5; i++)state[i] = thinking;}}

Page 124: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.124Operating System Concepts

Fig 7.22 A monitor solution to the Dining- Philosophers (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 neighborstest((i+4) % 5); //唤醒可能在 self[i+4]上阻塞的进程test((i+1) % 5); //唤醒可能在 self[i+1]上阻塞的进程}

Page 125: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.125Operating System Concepts

Fig 7.22 A monitor solution to the Dining- Philosophers (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();

}}

Page 126: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.126Operating System Concepts

Fig 7.22 A monitor solution to the Dining- Philosophers (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

Page 127: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.127Operating System Concepts

Monitor Implementation Using Semaphores[*] Variables

semaphore mutex; // (initially = 1)semaphore next; // (initially = 0)int next-count = 0;

Each external procedure F will be replaced bywait(mutex); … body of F; …

if (next-count > 0)signal(next)else

signal(mutex); Mutual exclusion within a monitor is ensured.

Page 128: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.128Operating System Concepts

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--;

Page 129: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.129Operating System Concepts

Monitor Implementation

The operation x.signal can be implemented as:

if (x-count > 0) {next-count++;signal(x-sem);wait(next);next-count--;

}

Page 130: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.130Operating System Concepts

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.

Page 131: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.131Operating System Concepts

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.必须保证不同步进程不忽略管程提供了的互斥网关,并且试图直接存取共享资源 , 没有使用存取协议。

Page 132: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.132Operating System Concepts

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(十字转门 ,栅门 ) 排列等待需要适应互斥或读者 -写者锁的线程列表

Page 133: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.133Operating System Concepts

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 (挂起锁),即一般的锁,会挂起(阻塞)进程的执行

Page 134: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.134Operating System Concepts

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不可用状态。

Page 135: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.135Operating System Concepts

Windows 2000/XP 的进程互斥和同步

返回

在Windows 2000/XP 中提供了互斥对象、信号量对象和事件对象等三种同步对象和相应的系统调用,用于进程和线程同步。从本质上讲,这组同步对象的功能是相同的,它们的区别在于适用场合和效率会有所不同。对象名称是由用户给出的字符串。不同进程中用同样的名称来创建或打开对象,从而获得该对象在本进程的句柄。对象状态可分成可用和不可用两种。对象可用 (signaled state)表示该对象不被任何线程使用或所有;而对象不可用(nonsignaled state)表示该对象被某线程使用。

Page 136: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.136Operating System Concepts

Windows 2000/XP 的进程互斥和同步 -1 互斥对象 (Mutex)相当于互斥信号量,在一个时刻只能被一个线程使用。 信号量对象 (Semaphore) 是资源信号量,它的取值在 0到指定最大值之间,用于限制并发访问的线程数。 事件对象 (Event)相当于“触发器”,可通知一个或多个线程某事件的出现。 临界区对象 (Critical Section) 只能用于在同一进程内使用的临界区,同一进程内各线程对它的访问是互斥进行的。 互锁变量访问是最基本的互斥手段,其他的互斥和共享机制都是以它为基础的。它相当于硬件 TS指令。用于对整型变量的操作,可避免线程间切换对操作连续性的影响。

Page 137: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.137Operating System Concepts

7.9 Atomic Transactions[*]原子事务处理To use database-systems techniques in operating system7.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回退 .

Page 138: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.138Operating System Concepts

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.

Page 139: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.139Operating System Concepts

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 并行的原子事务处理

Page 140: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.140Operating System Concepts

Ex. 7.4Dekker算法7.4 第一个公认的解决两进程(线程)临界区问题的算法是由 Dekker 提出的,故称为 Dekker算法。算法如下所示。说明该算法满足临界区问题的三个必要条件。

共享变量:int turn, 初值为 0;Boolean flag[2] ,初值均为 false;

Pi(i=0,1)

Page 141: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.141Operating System Concepts

while(1) {

flag[ i ] = true;

while (flag[j]) {

if (turn==j) {

flag[ i ] = false;

while ( turn == j );

flag[ i ] = true;

}

}

CS

turn = j;

flag[ i ] = false;

RS

}

1. 互斥 (mutual exclusion)

A) Pi和 Pj 不可能同时进入 CS:

turn==j 和 turn==I 不会同时满足 B) 一个进程 (如 Pi)先进入 CS,则 flag[ i ]为 true,则 Pj 无法进入2. 前进 (progress)

A)Pi申请进入, Pj 不想进入,则flag[ i ]==false,Pi 顺利进入 B)Pi和 Pj 都想进入,则 turn==j时 Pj 进入, turn==i时 Pi 进入3. 有限等待 (bounded waiting)

Pi离开 CS 后,置 turn=j,flag[ i ]=false,这时 Pj 可以进入,如果 Pj 没有进入, Pi又执行了 falg[ i ]=true,则由于 turn==j ,所以 Pi 无法进入,而 Pj 可以进入

Ex. 7.4Dekker算法 (2)

Page 142: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.142Operating System Concepts

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;

算法描述如下页证明该算法满足临界区问题的所有要求。

Page 143: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.143Operating System Concepts

While(1) { while(1) { flag[i] = want_in; j = turn; while (j !=i) { if (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) j ++ ; if ((j>=n)&&(turn==i||flag[turn]==idle)) break; }

turn = i ; CS j = (turn+1)%n; while(flag[j]==idle) j=(j+1)%n;

turn=j; flag[i]=idle; RS}

1. 互斥 (mutual exclusion)

A) 两个进程 Px和 Py 不可能同时进入 CS:

turn==x 和 turn==y 不会同时满足,故 Px和Py 的两个 if 条件不会都满足 B) 一个进程 (如 Px)先进入 CS,则turn==x, flag[turn]==in_cs,则其他进程无法进入2. 前进 (progress)

A)Px申请进入,其他进程不想进入,则其他进程 flag均为 idle,则 Px的 j>=n 成立, if 条件成立,跳出 while ,进入 CS

B) 若干进程想进入,如 Pturn也想进入,则Pturn优先进入;否则,编号在 turn 后的最小号的想进入的进程进入 CS

3. 有限等待 (bounded waiting)

Pi离开 CS 时,置 turn 为想进入的进程中大于 turn 的最小欲进入之进程号,该进程就进入。进程 Pk 不会饿死,最多等待( k-turn) 个进程的 CS 执行

Ex. 7.5Eisenberg and McGuire’s algorithm(2)

Page 144: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.144Operating System Concepts

Ex. 7.8 理发问题7.8 理发问题:一个理发店内有一张沙发,可以坐 n个等待理发的顾客,理发室内有一张理发椅。当没有顾客时,理发师就休息;当一个新顾客进来时,如果所有的座位上都有人,他就离开理发店;如果沙发上有空位,他就坐下;如果理发师在休息,顾客就唤醒他让他为其理发。试用信号量来同步理发师和顾客的行为。

Page 145: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.145Operating System Concepts

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);}

Ex. 7.8 理发问题 (2)

Page 146: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.146Operating System Concepts

Ex. 7.9抽烟问题7.9抽烟问题:有一个烟草代理和三个抽烟者。抽烟者若要抽烟,必须具有烟叶、烟纸和火柴。三个抽烟者中,一人缺烟叶、一人缺烟纸、一人缺火柴。烟草代理会源源不断地分别供应烟叶、烟纸和火柴,并将他们放在桌上。如果他放的是烟叶,则缺烟叶的抽烟者拾起烟叶,制作香烟,然后抽烟;其他类推。试用信号量同步烟草代理和三个抽烟者。

Page 147: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.147Operating System Concepts

Semaphore smoker[3]; // 初始 0 ,三个抽烟者Semaphore material[3]; // 初始 0 ,三种原料Semaphore agent; // 初始 1 ,供应商Int turn; // 初始 0 ,轮到谁Agent:While(1){ wait(agent); signal(smoker[turn]); signal(material[(turn+1)%3]); signal(material[(turn+2)%3]); turn= (turn+1)%3;}

Smoker-i:While(1){ wait(smoker[i]); wait(material[(i+1)%3]); wait(material[(i+2)%3]); signal(agent);}

Ex. 7.9抽烟问题 (2)

Page 148: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.148Operating System Concepts

Ex. 7.11

7.11 写一个管程( monitor )用于实现有限缓冲区的生产者-消费者问题,要求将有限缓冲区置于管程内。

Page 149: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.149Operating System Concepts

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;}}

Producer process:While(1) { produce an item; bounded_buffer.put_item();}

Consumer process:While (1) { bounded_buffer.get_item(); consume the item;}

Ex. 7.11(2)

Page 150: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.150Operating System Concepts

2003 年硕士研究生入学考试试题 24. 关于临界区问题( 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

Page 151: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.151Operating System Concepts

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 )。请说明它的正确性,或指出错误所在。

若此时进程切换,且让对方再次进入临界区,互斥条件无法满足

Page 152: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.152Operating System Concepts

2000年硕士研究生入学考试试题 3 (10分 )

信号量如果只能取 0 或 1 为值,就变成了二元信号量。二元信号量更容易实现。而且,信号量可以由二元信号量替换。以下所列函数试图用二元信号量操作 waitB()和 signalB() 替换信号量 wait()、 signal():…… 其中,用于互斥的二元信号量 mutex 初始化为 1 ,用于进程挂起的二元信号量 delay 初始化为 0 。请指出该替换算法的错误所在。

Page 153: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.153Operating System Concepts

2000年硕士研究生入学考试试题 3 (2)

wait(semaphore s){

waitB(mutex); s = s-1; if (s<0) { signalB(mutex); waitB(delay); } else signalB(mutex);

}

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) 前交出 CPU2、 p3 and p4 call signal() 。此时本应允许 p1 and p2 wakeup ,但因 delay升至 1 后无法再升,导致 p1 or p2 中一个仍在 wait(delay)

Page 154: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.154Operating System Concepts

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 End

Page 155: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.155Operating System Concepts

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

Page 156: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.156Operating System Concepts

2005年硕士研究生入学考试试题 2试题 2 ( 10 分)试就 Mutual Exclusion 、 Progress、 Bounded

Waiting 论述以下解决双进程临界区问题的算法是错误的:Process P0:

do {flag[0] =true;while (flag[1]);

critical sectionflag[0] =false;

remainder section} while (1);

Process P1:do {

flag[1] =true;while (flag[0]);

critical sectionflag[1] =false;

remainder section} while (1);

Page 157: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.157Operating System Concepts

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 分)

不满足

Page 158: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.158Operating System Concepts

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运行时有无等待现象? 若有,在什么时候发生等待现象?

Page 159: Chapter 7:  Process Synchronization 进程同步

Silberschatz, Galvin and Gagne 20027.159Operating System Concepts

Exercises

4, 8, 11