夜雨聆风学习资料网 资料列表 开通 VIP 用登录 / 注册 ⌄
PDF

操作系统_第2章_进程与线程_2026考研专业课_202026计算机_202026计算机_2026年优路计算机408_02.基础阶段_01.考研电子信息基础精讲课程_01.操作系统基础精讲课程

查看资料信息、公开预览和下载状态。

共 221 页PDF · 3.6MB
下载

文档在线预览

公开展示前 10 页
100%
1
《操作系统_第2章_进程与线程_2026考研专业课_202026计算机_202026计算机_2026年优路计算机408_02.基础阶段_01.考研电子信息基础精讲课程_01.操作系统基础精讲课程》第1页预览
2
《操作系统_第2章_进程与线程_2026考研专业课_202026计算机_202026计算机_2026年优路计算机408_02.基础阶段_01.考研电子信息基础精讲课程_01.操作系统基础精讲课程》第2页预览
3
《操作系统_第2章_进程与线程_2026考研专业课_202026计算机_202026计算机_2026年优路计算机408_02.基础阶段_01.考研电子信息基础精讲课程_01.操作系统基础精讲课程》第3页预览
4
《操作系统_第2章_进程与线程_2026考研专业课_202026计算机_202026计算机_2026年优路计算机408_02.基础阶段_01.考研电子信息基础精讲课程_01.操作系统基础精讲课程》第4页预览
5
《操作系统_第2章_进程与线程_2026考研专业课_202026计算机_202026计算机_2026年优路计算机408_02.基础阶段_01.考研电子信息基础精讲课程_01.操作系统基础精讲课程》第5页预览
6
《操作系统_第2章_进程与线程_2026考研专业课_202026计算机_202026计算机_2026年优路计算机408_02.基础阶段_01.考研电子信息基础精讲课程_01.操作系统基础精讲课程》第6页预览
7
《操作系统_第2章_进程与线程_2026考研专业课_202026计算机_202026计算机_2026年优路计算机408_02.基础阶段_01.考研电子信息基础精讲课程_01.操作系统基础精讲课程》第7页预览
8
《操作系统_第2章_进程与线程_2026考研专业课_202026计算机_202026计算机_2026年优路计算机408_02.基础阶段_01.考研电子信息基础精讲课程_01.操作系统基础精讲课程》第8页预览
9
《操作系统_第2章_进程与线程_2026考研专业课_202026计算机_202026计算机_2026年优路计算机408_02.基础阶段_01.考研电子信息基础精讲课程_01.操作系统基础精讲课程》第9页预览
10
《操作系统_第2章_进程与线程_2026考研专业课_202026计算机_202026计算机_2026年优路计算机408_02.基础阶段_01.考研电子信息基础精讲课程_01.操作系统基础精讲课程》第10页预览

本文档共 221 页 剩余 211 页未展示,请下载后查阅

下载

文档文本内容

操作系统
第二章 进程与线程内 容
基础:进程描述及控制
1
2 实现:互斥与同步
3 避免:死锁与饥饿
4 解决:几个经典问题
5 关于:进程通信
6 策略:进程调度Learning objectiv
By the end of this lecture you should be able to:
lExplain what’s Process, Swapping and Thread
l掌握分析进程的结构, PCB, Process image(进程映像)
l描述进程的基本状态及转换规则与原因
l区别进程的挂起与阻塞状态
l理解OS内核的主要功能
l理解Process Control Primitives(原语)
l区别Process Switching vs. Mode Switching
l区别Process vs. ThreadM a j o r R e q u i r e m e n t s o f a n O p e r a t i n g
S y s t e m
l Interleave the execution of several processes to maximize processor utilization
while providing reasonable response time
l Allocate resources to processes
l Support interprocess communication and user creation of processes程序的执行顺序
l 程序顺序执行
n 程序顺序执行时的特征:顺序性、封闭性、可再现性
l 程序并发执行
n 程序并发执行时的特征:间断性、非封闭性、不可再现性
l 程序并发执行条件(Bernstein条件)
n R(P1)∩W(P2)∪W(P1)∩R(P2)∪W(P1)∩W(P2) = { }P r o c e s s
l Also called a task
l Execution of an individual program
n 进程是程序在一个数据集合上的运行过程,是系统进行资源分配和调度的
一个独立单位
n 进程是可并发执行的程序在一个数据集合上的运行过程
l Can be traced
n list the sequence of instructions that executeC h a r a c t e r i s t i c s o f P r o c e s s
l Dynamic(动态性)
l Concurrency(并发性)
l Independent(独立性)
l Asynchronous(异步性)P r o c e s s S t r u c t u r e
l Programs
l Datas
l PCB (Process Control Block 进程控制块)第8 - 9讲 进程状态转换P r o c e s s S t a t e s
l 进程的并发执行
l 进程的2状态
l 进程的5状态
l 进程状态转换图假设内存中有3个进程A、B、C,他们的程序代码已全部装入内存。若A、
C两进程需要执行12条指令,B进程需要执行4条指令,且B进程执行到第
4条指令处必须等待I/O。如何跟踪他们的执行过程?D i s p a t c h e r
操作系统重要组件
●
负责进程、线程、作业的调度与分配
●
提供多种调度算法如先来先服务、短作业优先、时间片轮转等
●
监测性能变化,如CPU使用率、IO响应时间等
●T w o - S t a t e P r o c e s s M o d e l
l Process may be in one of two states
n Running(执行)
n Not-running(非执行)N o t - R u n n i n g P r o c e s s i n a Q u e u e注:
l 并非所有进程只要Not-running就处于ready(就绪) ,有的需要blocked(阻塞)等待I/O完成
l Not-running又可分为 ready和blocked两种状态l Running (运行)
l Ready (就绪)
l Blocked (阻塞)
l New (创建)
l Exit (终止)l Running:占用处理机(单处理机环境中,某一时刻仅一个进程占用处理机)
l Ready:准备执行
l Blocked:等待某事件发生才能执行,如等待I/O完成等
l New:进程已经创建,但未被OS接纳为可执行进程
l Exit:因停止或取消,被OS从执行状态释放lNull New:新创建进程首先处于新状态
lNew Ready:OS接纳新状态进程为就绪进程
lReady Running:OS只能从就绪进程中选一个进程
执行
lRunning Exit:执行状态的进程执行完毕,或被取
消,则转换为退出状态
lRunning Ready:分时系统中,时间片用完,或优
先级高的进程到来,将终止优先级低的进程的执行lRunning Blocked:执行进程需要等待某事件发生。
通常因进程需要的系统调用不能立即完成,而阻塞
lBlocked Ready:当阻塞进程等待的事件发生,就
转换为就绪状态
lReady Exit:某些系统允许父进程在任何情况下终
止其子进程。若一个父进程终止,其子孙进程都必须终
止。
lBlocked Exit:同前U s i n g T w o Q u e u e sSwapping(对换技术,交换技术)
将内存中暂时不能运行的进程,或暂时不用的数据和程序,Swapping-out到
外存,以腾出足够的内存空间,把已具备运行条件的进程,或进程所需要的数
据和程序,Swapping-in内存。Swapping(对换技术,交换技术)
note
应该保证进程执行时间比交换时间长
交换空间通常作为磁盘的一整块,且独立于文件系统
普通的交换技术一般很少使用,交换技术的一些变体任然在UNIX等系统中使用S u s p e n d e d P r o c e s s e s
l Processor is faster than I/O so all processes could be
waiting for I/O
l Swap these processes to disk to free up more memory
l Blocked state becomes suspend state when swapped to diskR e a s o n s f o r P r o c e s s S u s p e n s i o n被挂起进程的特征
l 不能立即执行
l 可能是等待某事件发生。若是,则阻塞条件独立于挂起条件,即使
阻塞事件发生,该进程也不能执行
l 使之挂起的进程为:自身、其父进程、OS
l 只有挂起它的进程才能使之由挂起状态转换为其他状态S u s p e n d vs. B l o c k e d ( 挂 起 与 阻 塞 )
问题
1.是否只能挂起阻塞进程?
2.如何激活一个挂起进程?S u s p e n d vs. B l o c k e d
l 区分两个概念:
? 进程是否等待事件,阻塞与否
? 进程是否被换出内存,挂起与否
l 4种状态组合:
Ready:进程在内存,准备执行
Blocked:进程在内存,等待事件
Ready, Suspend:进程在外存,只要调入内存
即可执行
Blocked,Suspend:进程在外存,等待事件注:
处理机可调度执行的进程有两种:
l 新创建的进程
l 或换入一个以前挂起的进程
通常为避免增加系统负载,系统会换入一个以前挂起的进程执行。O n e S u s p e n d S t a t e
此方案存在问题!T w o n e w s t a t e s
- Blocked, suspend
- Ready, suspendT w o S u s p e n d S t a t e s具有挂起状态的进程状态转换
lBlocked Blocked, Suspend :OS通常将阻塞进程换出,
以腾出内存空间
lBlocked, Suspend Ready, Suspend:当Blocked,
Suspend进程等待的事件发生时,可以将其转换为Ready,
Suspend
lReady, Suspend Ready:OS需要调入一个进程执行时
lReady Ready, Suspend :一般,OS挂起阻塞进程。但有
时也会挂起就绪进程,释放足够的内存空间
lNew Ready, Suspend(New Ready):新进程创建后,可
以插入到Ready队列或Ready, Suspend队列。若无足够的内
存分配给新进程,则需要New Ready, Suspend具 有 挂 起 状 态 的 进 程 状 态 转 换 ( 续 )
lBlocked, Suspend Blocked:当Blocked,Suspend队列中有一个进程的阻塞事
件可能会很快发生,则可将一个Blocked, Suspend进程换入内存,变为Blocked
lRunning Ready, Suspend :当执行进程的时间片用完时,会转换为Ready。
或,一个高优先级的Blocked, Suspend进程正好变为非阻塞状态,OS可以将执
行进程转换为Ready,Suspend状态
lAll Exit:通常,Running Exit。但某些OS中,父进程可以终止其子进程,
使任何状态的进程都可转换为退出状态P r o c e s s D e s c r i p t i o n
问题:
OS如何感知进程、控制进程及其所用的系统资源?Operating System Control Structures
l Information about the current status of each process and
resource
l Tables are constructed for each entity the operating
system manages
Memory Tables
- I/O Tables
- File Tables
- Process TableM e m o r y T a b l e s
l Allocation of main memory to processes.
l Allocation of secondary memory to processes.
l Protection attributes for access to shared memory regions.
l Information needed to manage virtual memory(虚拟存储).I / O T a b l e s
l I/O device is available or assigned.
l Status of I/O operation.
l Location in main memory being used as the source or
destination of the I/O transfer.F i l e T a b l e s
l Existence of files.
l Location on secondary memory.
l Current Status.
l Attributes.
l Sometimes this information is maintained by a file-management system.P r o c e s s T a b l e
l Where process is located.
l Attributes necessary for its management.
● Process ID
● Process state
● Location in memoryP r o c e s s L o c a t i o n
l Process includes set of programs to be executed.
● Data locations for local and global variables.
● Any defined constants.
● Stack.
l Process control block(PCB).
● Collection of attributes.
l Process image(进程映像)
● Collection of program, data, stack, and attributes.P r o c e s s i m a g e
l User Data
l User Program
l System Stack:存放系统及过程调用地址、参数
l Process Control Block(PCB):OS感知进程、控制进程的数据结构P r o c e s s C o n t r o l B l o c k
l 简称PCB:是OS控制和管理进程时所用的基本数据结构
l 作用:PCB是相关进程存在于系统中的唯一标志;系统根据PCB而感知相关
进程的存在。
l 内容:通常情况下,PCB包含Identifiers(标识)、状态、控制、指针等
多种信息。P r o c e s s C o n t r o l B l o c k ( P C B )
lProcess identification
Identifiers
●
Identifier of this process (进程ID)
●
Identifier of the process that created
●
this process (parent process) (父进程ID)
User identifier (用户ID)
●P r o c e s s C o n t r o l B l o c k
l Processor State Information
§ User-Visible Registers(用户可见寄存器)
A user-visible register is one that may be referenced by means
•
of the machine language that the processor executes.
Typically, there are from 8 to 32 of these registers, although
•
some RISC implementations have over 100.P r o c e s s C o n t r o l B l o c k
l Processor State Information
Control and Status Registers
●
There are a variety of processor registers that are employed to
control the operation of the processor. These include
Program counter: Contains the address of the
●
next instruction to be fetched.
Condition codes: Result of the most recent
●
arithmetic or logical operation (e.g., sign,
zero, carry, equal, overflow).
Status information: Includes interrupt
●
enabled/disabled flags, execution mode .P r o c e s s C o n t r o l B l o c k
l Processor State Information
● Stack Pointers
Each process has one or more last-in-first-out (LIFO)
●
system stacks associated with it.
A stack is used to store parameters and calling
●
addresses for procedure and system calls.
The stack pointer points to the top of the stack.
●P r o c e s s C o n t r o l B l o c k
l Process Control Information
● Scheduling and State Information
Process state: defines the readiness of the
•
process to be scheduled for execution (e.g.,
running, ready, waiting, halted).
Priority: One or more fields may be used to
●
describe the scheduling priority of the
process.
Scheduling-related information: This will
●
depend on the scheduling algorithm used.
Event: Identity of event the process is
●
awaiting before it can be resumedP r o c e s s C o n t r o l B l o c k
l Process Control Information
● Data Structuring
A process may be linked to other process
●
in a queue, ring, or some other structure.
A process may exhibit a parent-child
●
(creator-created) relationship with
another process.
The process control block may contain
●
pointers to other processes to support
these structures.P r o c e s s C o n t r o l B l o c k
l Process Control Information
● Interprocess Communication
Various flags, signals, and messages may be associated
●
with communication between two independent processes.
● Process Privileges
Processes are granted privileges in terms of the memory
●
that may be accessed and the types of instructions that
may be executed.P r o c e s s C o n t r o l B l o c k
l Process Control Information
● Memory Management
This section may include pointers to segment
●
and/or page tables that describe the virtual
memory assigned to this process.
● Resource Ownership and Utilization
Resources controlled by the process may be
●
indicated, such as opened files. A history
of utilization of the processor or other
resources may also be included; this
information may be needed by the scheduler.P r o c e s s C o n t r o l B l o c k(资源管理功能)
l Process Management:进程创建和终止、调度、状态转换、同步和通
信、管理PCB
l Memory Management:为进程分配地址空间、对换、段/页管理
l I/O Management:缓存管理、为进程分配I/O通道和设备Typical Function of an OS Kernel(支撑功能)
l Interrupt handling(中断处理)
l Timing(时钟管理)
l Primitive(原语): Atomic Operation
l Accounting(统计)
l Monitoring(监测)P r o c e s s C o n t r o l P r i m i t i v e s ( 原 语 )
l Process Switch,进程切换
l Create and Terminate, 创建与终止
l Block and Wakeup, 阻塞与唤醒
l Suspend and Activate, 挂起与激活W h e n t o S w i t c h a P r o c e s s
l Clock interrupt
● process has executed for the maximum allowable time slice
(时间片)
l I/O interrupt
l Memory fault(存储访问失效)
● memory address is in virtual memory so it must be brought
into main memoryW h e n t o S w i t c h a P r o c e s s
l Trap(陷阱)
● error occurred
● may cause process to be moved to Exit state
l Supervisor call(管理程序调入)
● such as file openC h a n g e o f P r o c e s s S t a t e
l Save context of processor including program counter and other
registers
l Update the PCB of the process that is currently running
l Move PCB to appropriate queue - ready, blocked
l Select another process for executionC h a n g e o f P r o c e s s S t a t e
l Update the PCB of the process selected
l Update memory-management data structures
l Restore context of the selected processP r o c e s s S w i t c h i n g vs. M o d e
S w i t c h i n g
l Process Switch, 是作用于进程之间的一种操作。
当分派程序收回当前进程的CPU 并准备把它分派
给某个就绪进程时,该操作将被引用。
l Mode Switch 是进程内部所引用的一种操作。当
进程映像所包含的程序引用核心子系统所提供的
系统调用时,该操作将被引用。P r o c e s s C r e a t i o n
l Submission of a batch job
l User logs on
l Created to provide a service such as printing
l Process creates another processP r o c e s s C r e a t i o n ( c r e a t ( ) 原 语 , 步
骤 )
1.为进程分配一个唯一标识号ID: 主进程表中增加一个新的表项
2.为进程分配空间 : 用户地址空间、用户栈空间、PCB空间。若
共享已有空间,则应建立相应的链接。
3.初始化PCB:进程标识、处理机状态信息、进程状态
4.建立链接 :若调度队列是链表,则将新进程插入到就绪或(就
绪,挂起)链表
5.建立或扩展其他数据结构P r o c e s s T e r m i n a t i o n ( 终 止 )
l Batch job issues Halt instruction
l User logs off
l Quit(退出) an application
l Error and fault conditionsR e a s o n s f o r P r o c e s s T e r m i n a t i o n
l Normal completion, 正常结束
l Time limit exceeded, 超时终止,执行时间超过预计时间
l Memory unavailable, 内存不足,无法为进程分配所需的内存空间
l Bounds violation, 越界访问
l Protection error, 企图使用未允许用的数据,或操作方式错
l Arithmetic error, 计算错,如除零,或企图存储硬件允许的最大数
l Time overrun, 超时等待某事件发生R e a s o n s f o r P r o c e s s T e r m i n a t i o n
lI/O failure, 如找不到文件或多次重试仍无法读写文件,或无效操作
lInvalid instruction, 企图执行不存在的指令
lPrivileged instruction, 企图执行特权指令
lData misuse,数据类型不符,或未初始化
lOperating system intervention,操作员或OS干预,如发生死锁的时候
lParent terminates, so child processes terminate
lParent requestP r o c e s s T e r m i n a t i o n ( d e s t r o y ( ) 原 语 ,
步 骤 )
1. 根据被终止进程的标识符ID,找到其PCB,读出该进程的状态;
2. 若该进程为执行状态,则终止其执行,调度新进程执行;
3. 若该进程有子孙进程,则立即终止其所有子孙进程
4. 将该进程的全部资源,或归还给其父进程,或归还给系统
5. 将被终止进程(的PCB)从所P r o c e s s B l o c k a n d W a k e u p ( 阻 塞 的 原
因 )
l 请求系统服务
l 启动某种操作:如I/O
l 新数据尚未到达
l 无新工作可做P r o c e s s B l o c k a n d W a k e u p ( 原 语 )
l 阻塞原语block()
当出现阻塞事件,进程调用阻塞原语将自己阻塞。状态
变为“阻塞状态”,并进入相应事件的阻塞队列
l 唤醒原语wakeup()
当阻塞进程期待的事件发生,有关进程调用唤醒原语,
将等待该事件的进程唤醒。状态变为Ready,插入就绪队列P r o c e s s B l o c k a n d W a k e u p ( 原 语 )
l 挂起原语suspend()
当出现挂起事件,系统利用挂起原语将指定进程或阻
塞状态进程挂起。进程从内存换到外存,状态改变:
Ready Ready,Suspend; Blocked
Blocked,Suspend,插入相应队列
l 激活原语active()
当激活事件发生,系统利用激活原语将指定进程激活。
进程从外存换入到内存,状态改变:Ready,Suspend
Ready ;Blocked,Suspend Blocked ,插入相应队列T h r e a d ( 线 程 )
l An execution state (running, ready, etc.)
l Saved thread context when not running.
l Has an execution stack.
l Some per-thread static storage for local variables.
l Access to the memory and resources of its process.
● all threads of a process share this.B e n e f i t s o f T h r e a d s
lTakes less time to create a new thread than a
process.
lLess time to terminate a thread than a process.
lLess time to switch between two threads within
the same process.
lSince threads within the same process share
memory and files, they can communicate with
each other without invoking the kernel.T h r e a d s
l Suspending a process involves suspending all threads of
the process
● since all threads share the same address space.
l Termination of a process, terminates all threads within
the process.M u l t i t h r e a d i n g
lOperating system supports multiple threads of
execution within a single process.
lMS-DOS supports a single thread.
lUNIX supports multiple user processes but only
supports one thread per process.
lWindows 2000, Solaris, Linux, Mach, and OS/2
support multiple threads.T h r e a d S t a t e s
l Key states for a thread: Running, Ready, Blocked.
l Operations associated with a change in thread state.
● Spawn(派生),Spawn another thread
● Block
● Unblock
● FinishU s e r - L e v e l T h r e a d s
l All thread management is done by the application.
l The kernel is not aware of the existence of threads.
l 描述此类线程的数据结构以及控制此类线程的原语在核外子系统中实现。K e r n e l - L e v e l T h r e a d s
l W2K, Linux, and OS/2 are examples of this approach.
l Kernel maintains context information for the process and
the threads.
l Scheduling is done on a thread basis.
l描述此类线程的数据结构以及控制此类线
程的原语在核心子系统中实现。C o m b i n e d A p p r o a c h e s
l Example is Solaris.
l Thread creation done in the user space.
l Bulk(大批) of scheduling and synchronization of threads
done in the user space.R e l a t i o n s h i p B e t w e e n T h r e a d s a n d
P r o c e s s e s
Threads:Process Description Example Systems
1:1 Each thread of execution is
Traditional UNIX
a
implementations
unique process with its own
address space and resources.
M:1 A process defines an address
Windows NT, Linux,
space and dynamic resource
Solaris, OS/2,
ownership. Multiple threads
OS/390, MACH
may be created and executed
within that process.R e l a t i o n s h i p B e t w e e n T h r e a d s a n d
P r o c e s s e s
Threads:Process Description Example Systems
A thread may migrate from one
1:M Ra (Clouds),
process environment to
Emerald
another. This allows a thread
to be easily moved among
distinct systems.
TRIX
M:M Combines attributes of M:1
and 1:M cases第13讲 进程调度的目标与类型Types of scheduling
1
Scheduling Criteria(准则)
2
Scheduling Algorithms
3
Real-Time Scheduling
4A i m o f S c h e d u l i n g
l Response time(响应时间)
l Throughput(系统吞吐量)
l Processor efficiency(处理机效率)
l Fairness (公平性,防止进程饥饿)T y p e s o f S c h e d u l i n g
l 按OS的类型划分:
§ 批处理调度、分时调度、实时调度、多处理机调度
l 按调度的层次划分:
Long-term scheduling(长程调度)
•
Medium-term scheduling(中程调度)
•
Short-term scheduling(短程调度)
•L o n g - t e r m s c h e d u l i n g
l 又称为高级调度、作业调度,它为被调度作业或用户程序创建进程、分配
必要的系统资源,并将新创建的进程插入就绪队列,等待Short-term
scheduling
采用交换技术的系统将新创建的进程插入(就绪,挂起)
•
队列,等待Medium-term scheduling 。
批处理系统中,作业进入系统后,先驻留在磁盘上(批
•
处理队列中)。长程调度从该队列中选择作业,为之创建
进程L o n g - t e r m s c h e d u l i n g
l Determines which programs are admitted to the system for
processing
- 这取决于调度算法,如FCFS、短作业优先、基于优
先权、响应比高者优先等调度算法
l How many programs are admitted to the system ?
- Controls the degree of multiprogramming
l When does the scheduler be invoked?
Each time a job terminates
-
- Processor is idle exceeds a certain
thresholdM e d i u m - t e r m s c h e d u l i n g
l 又称为中级调度,它调度换出到磁盘的进程进入
内存,准备执行
中级调度配合对换技术使用。
•
其目的是为了提高内存的利用率和系统吞吐量。
•
在多道程序度允许的情况下,从外存选择一个挂起状态的
•
进程调度到内存(换入)S h o r t - t e r m s c h e d u l i n g
l 又称为进程调度、低级调度,调度内存中的就绪
进程执行。
l Known as the dispatcher:决定就绪队列Which
进程将获得处理机
l Executes most frequently
l Invoked when an event occurs
§ Clock interrupts
§ I/O interrupts
§ Operating system calls
§ Signals(信号)第14讲 进程调度原则与策略U s e r - o r i e n t e d
l Response Time(响应时间)
- Elapsed time between the submission of a request until
there is output.
- 常用于评价分时系统的性能。
l Turnaround time(周转时间)
- 是指从作业提交给系统开始,到作业完成为止的这段时间间隔(也称
为作业周转时间)
- 常用于评价批处理系统的性能。U s e r - o r i e n t e d
l Deadlines(截止时间)
- 是指某任务必须开始执行的最迟时间(Starting deadline ),
或必须完成的最迟时间 (Completion deadline )
- 常用于评价实时系统的性能。S y s t e m - o r i e n t e d
l Throughput(吞吐量)
- 单位时间内系统所完成的作业数
- 用于评价批处理系统的性能
l 处理机利用率
- This is the percentage of time that the processor
is busy.
- E f f e c t i v e a n d e f f i c i e n t u t i l i z a t i o n o f t h e
processor.S y s t e m - o r i e n t e d
l Balancing Resource(资源平衡)
- Keep the resources of the system busy.
- 适用于长程调度和中程调度
l Fairness(公平性)
- Process should be treated the same, and
no process should suffer starvation.P r i o r i t i e s
l Scheduler will always choose a process of
higher priority over one of lower priority.
l Have multiple Ready queues to represent
each level of priority.
l Lower-priority may suffer starvation.
§ allow a process to change its priority based on
its age (生存期)or execution history.第15 - 16讲 进程调度算法D e c i s i o n M o d e
l Nonpreemptive(非剥夺方式)
§ Once a process is in the running state, it will
continue until it terminates or blocks itself
for I/O.
§ 主要用于批处理系统。
l Preemptive(剥夺方式)
§ Currently running process may be interrupted
and moved to the Ready state by the operating
systemD e c i s i o n M o d e
l Preemptive(剥夺方式)
● Allows for better service since any one process cannot
monopolize the processor for very long.
● 主要用于实时性要求较高的实时系统及性能要求较高的批处理系统和分时
系统。线 程 调 度
用户级线程调度
●
内核级线程调度
●P r o c e s s S c h e d u l i n g E x a m p l e
例如,有5个进程,描述如下:
进程 到达时刻 服务时间
P1 0 3
P2 2 6
P3 4 4
P4 6 5
P5 8 2以下部分介绍用6种不同的短程调度算法调度这5
个进程,比较各种调度算法的平均周转时间。分
析各种调度算法的优缺点。F i r s t - C o m e - F i r s t - S e r v e d ( F C F S )
5
0 10 15 20
1
2
3
4
5
l Each process joins the Ready queue.
l When the current process ceases to execute,
the oldest process in the Ready queue is
selected.F i r s t - C o m e - F i r s t - S e r v e d ( F C F S )
l 计算进程的平均周转时间
l A short process may have to wait a very
long time before it can execute.
l Favors CPU-bound processes.
§ I/O processes have to wait until CPU-bound
process completes.F C F S i s u n f a i r t o s h o r t p r o c e s sFCFS算法的实际应用
l 一般,FCFS与其他调度算法混合使用。
l 系统可以按照不同的优先级维护多个就绪队列,
每个队列内部按照FCFS算法调度。Round Robin (RR,轮转法,时间片法)
l Uses preemption based on a clock.
l An amount of time is determined that allows each process to
use the processor for that length of time.
- Known as time slicing(时间片).
l Clock interrupt is generated at periodic intervals.
l When an interrupt occurs, the currently running process is
placed in the Ready queue.
- Next ready job is selectedRound Robin (RR,轮转法,时间片法)
5
0 10 15 20
1
2
3
4
5Round Robin (RR,轮转法,时间片法)
RR算法分析:
1.时间片的大小对计算机性能的影响
2.存在的问题:
-未有效利用系统资源。Processor-bound进程充分利用时间片,而
I/O- bound进程在两次I/O之间仅需很少的CPU时间,却需要等待一个时间
片。
-如何改进?V i r t u a l r o u n d r o b i n ( V R R )
l RR算法的改进:增加一个辅助队列,接收I/O阻塞完成的进程,调度优
先于就绪队列,但占用的处理机时间小于就绪队列的时间片。
l 算法分析:VRR算法比RR算法公平。
l RR算法常用于分时系统及事务处理系统。S h o r t e s t J o b F i r s t ( S J F , 短 作 业 优 先 )
lPolicy: Preemptive or Nonpreemptive?
lProcess with shortest expected processing time is
selected next.
lShort process jumps ahead of longer processes.
5
0 10 15 20
1
2
3
4
5S h o r t e s t J o b F i r s t ( S J F , 短 作 业 优 先 )
SJF算法分析:
1.改善了系统的性能,降低了系统的平均等待时间,
提高了系统的吞吐量
2.存在的问题:
很难准确确定进程的执行时间
•
对长进程不公平,Possibility of starvation for
•
longer processes
未考虑进程的紧迫程度,不适合于分时系统和事务处理
•
系统S h o r t e s t R e m a i n i n g T i m e ( S R T , 剩 余 时 间 最 短 者 优
先 )
l Preemptive version of shortest process next policy.
l Must estimate processing time.
5
0 10 15 20
1
2
3
4
5S h o r t e s t R e m a i n i n g T i m e ( S R T , 剩 余 时 间 最 短 者 优
先 )
SRT算法分析:
1.与SPN算法一样,很难准确确定进程的剩余执行时间,且对长进程不公平
2.但是,它不象FCFS算法偏袒长进程,也不象RR算法会产生很多中断而增加系统
负担。
3.由于短进程提前完成,故其平均周转时间比SPN短。H i g h e s t R e s p o n s e R a t i o N e x t ( H R R N , 响 应 比 高 者 优 先 )
l 响应比RR = (time spent waiting + expected service time) /
expected service time.
l Choose next process with the lowest response ratio.Highest Response Ratio Next (HRRN,响应比高者优先)
5
0 10 15 20
1
2
3
4
5H i g h e s t R e s p o n s e R a t i o N e x t ( H R R N , 响 应 比 高 者 优 先 )
HRRN算法分析:
1.若进程的等待时间相同,则要求服务时间短的进程优先 (SPN);
2.若进程要求的服务时间相同,则等待时间长的进程优先(FCFS);
3.长进程随着等待时间增加,必然会被调度。
4.但是,很难准确确定进程要求的执行时间,且每次调度之前需要计算响应
比,增加系统开销Feedback (FB,反馈调度法)
融合时间片轮转、优先级调度、多级队列调度
1.设置多个就绪队列,各队的优先权不同(从上而下优先
级逐级降低);
2.各个队列中进程执行的时间片不同,优先权愈高时间片
愈短;
3.新进程首先放入第一队列尾,按FCFS方法调度,若一个
时间片未完成,到下一队列排队等待;
4.仅当第一队列空时,调度程序才开始调度第二队列的进
程,依次类推。F e e d b a c k ( F B , 反 馈 调 度 法 )F e e d b a c k ( F B , 反 馈 调 度 法 )
5
0 10 15 20
1
2
3
4
5F e e d b a c k ( F B , 反 馈 调 度 法 )
算法分析:
1.有利于交互型作业 (常为短作业)
2.有利于短批处理作业
3.存在的问题:
-当不断有新进程到来,则长进程可能饥饿。内 容 2.6 - 2.7
1
2Learning objectiv 2.6 - 2.7
By the end of this lecture you should be able
to:
l Explain what’s Concurrency, ,
l 掌握2.6 - 2.7
By the end of this lecture you should be able
to:
l 掌握3个经典问题的解决方法:
l 理解
afe State vs. Unsafe StateD e s i g n I s s u e s o f C o n c u r r e n c y
l Communication among processes
l Sharing /Competing of resources
l Synchronization of multiple processes
l Allocation of processor timeD i f f i c u l t i e s w i t h C o n c u r r e n c y
l Sharing global resources
l Management of allocation of resources
l Programming errors difficult to locateA S i m p l e E x a m p l e
void echo()
{
chin = getchar();
chout = chin;
putchar(chout);
}A S i m p l e E x a m p l e
Process P1 Process P2
….
….
in = getchar(); in =
getchar();
…. ….
chout = in; chout =
in;
….
….
putchar(chout);
putchar(chout);
….
….O p e r a t i n g S y s t e m C o n c e r n s
l Keep track of active processes: PCB
l Allocate and deallocate resources
• Processor time: scheduling
• Memory: virtual memory
• Files
• I/O devices
l Protect data and resources
l Result of process must be independent of the speed of
execution of other concurrent processes.P r o c e s s I n t e r a c t i o n
lProcesses unaware of each other
- Competition
- Mutual exclusion, Deadlock, Starvation
lProcesses indirectly aware of each other
- Cooperation by sharing
- Mutual exclusion, Deadlock, Starvation, Data
coherence (一致性)
lProcess directly aware of each other
- Cooperation by communication
- Deadlock, StarvationC o m p e t i t i o n A m o n g P r o c e s s e s f o r
R e s o u r c e s
l Mutual Exclusion(互斥)
§ Critical sections(临界区)
Only one program at a time is allowed in its
•
critical section.
Eg. Only one process at a time is allowed to
•
send command to the printer(critical
resource).
l Deadlock(死锁)
l StarvationC o m p e t i t i o n A m o n g P r o c e s s e s f o r
R e s o u r c e s
Deadlock
例如,有两个进程P1、P2,竞争两个资源A、B。假设
占用:P1(B) and P2(A)
申请:P1(A) and P2(B)P 1 & P 2 - D e a d l o c kC o o p e r a t i o n A m o n g P r o c e s s e s b y
S h a r i n g
l Writing must be mutually exclusive.
l Critical sections are used to provide data integrity(数据
完整性).C o o p e r a t i o n A m o n g P r o c e s s e s b y C o m m u n i c a t i o n
l Messages are passed
§ Mutual exclusion is not a control requirement.
l Possible to have deadlock
§ Each process waiting for a message from the
other process.
l Possible to have starvation
§ Two processes sending message to each other
while another process waits for a message.R e q u i r e m e n t s f o r M u t u a l E x c l u s i o n
l Only one process at a time is allowed in the critical
section for a resource .
l A process that halts in its non-critical section must do
so without interfering with other processes.
l No deadlock or starvation.R e q u i r e m e n t s f o r M u t u a l E x c l u s i o n
l A process must not be delayed access to a critical section
when there is no other process using it.
l No assumptions are made about relative process speeds or
number of processes.
l A process remains inside its critical section for a finite
time only.R e q u i r e m e n t s f o r M u t u a l E x c l u s i o n
l 空闲让进
l 忙则等待
l 有限等待
l 让权等待A p p r o a c h e s o f M u t u a l E x c l u s i o n
l Software Approaches
l Hardware Support
l Semaphores
l Monitors
l Message PassingS o f t w a r e A p p r o a c h e s
l Memory access level
l Access to the same location in main memory are serialized by
some sort of memory arbiter .
l Dekker’s Algorithm
l Peterson’s AlgorithmS o f t w a r e A p p r o a c h e s
l To mutual exclusion for two processes.
l To illustrate most of the common bugs encountered in
developing concurrent programs.
l Is likely to have high processing overhead.
l The risk of logical errors is significant.进程的并发控制硬件实现方法A p p r o a c h e s o f M u t u a l E x c l u s i o n
l Software Approaches
l Hardware Support
l Semaphores
l Monitors
l Message PassingM u t u a l E x c l u s i o n : H a r d w a r e S u p p o r t
l Interrupt Disabling
§ A process runs until it invokes an operating-system service or
until it is interrupted.
§ Disabling interrupts guarantees mutual exclusion.
l The price of this approach is high.
l Multiprocessing
§ Disabling interrupts on one processor will not guarantee mutual
exclusion.M u t u a l E x c l u s i o n b y I n t e r r u p t
D i s a b l i n gM u t u a l E x c l u s i o n : H a r d w a r e
S u p p o r t
l Special Machine Instructions
§ Performed in a single instruction cycle.
§ Not subject to interference from other instructions.(避免冲突)
§ Reading and writing
§ Reading and testingM u t u a l E x c l u s i o n : H a r d w a r e
S u p p o r t
lTest and Set Instruction
function testset ( var i:integer ) :
boolean ;
begin
if i = 0 then
begin
i := 1;
testset := true;
end
else testset :=false;
end.M u t u a l E x c l u s i o n : H a r d w a r e
S u p p o r tM u t u a l E x c l u s i o n : H a r d w a r e
S u p p o r t
Exchange Instruction
procedure exchange ( var r :register; var m :memory );
var temp;
begin
temp := m;
m := r;
r := temp;
end.M u t u a l E x c l u s i o n : H a r d w a r e
S u p p o r t
program mutualexclusion;
const n=…; /*进程数*/
var bolt:integer;
procedure P(i:integer);
var key:integer;
begin
repeat
key:=1;
repeat exchange(key,bolt)
until key=0;
<临界区>;
bolt := 0;
<其余部分>
forever
end;M u t u a l E x c l u s i o n M a c h i n e
I n s t r u c t i o n s
l Advantages
§ Applicable to any number of processes on either
a single processor or multiple processors
sharing main memory.
§ It is simple and therefore easy to verify.
§ It can be used to support multiple critical
sections.M u t u a l E x c l u s i o n M a c h i n e
I n s t r u c t i o n s
l Disadvantages
● Busy-waiting is employed.
● Starvation is possible.
when a process leaves a critical section and more than
●
one process is waiting.
● Deadlock is possible.
● If a low priority process has the critical region and a higher priority process
needs, the higher priority process will obtain the processor to wait for the
critical region.信号量及
生产者/消费者、读者/写者问题A p p r o a c h e s o f M u t u a l E x c l u s i o n
l Software Approaches
l Hardware Support
l Semaphores
l Monitors
l Message PassingS e m a p h o r e s
l Special variable called a semaphore is used for signaling.
l If a process is waiting for a signal, it is blocked until
that signal is sent.
l Wait and Signal operations cannot be interrupted.
l Queue is used to hold processes waiting on the semaphore.S e m a p h o r e s
Semaphore is a variable that has an integer value.
May be initialized to a nonnegative number .
●
Wait and Signal are primitives (atomic,
●
cannot be interrupted and each routine can
be treated as an indivisible step).S e m a p h o r e s
l Wait operation decrements the semaphore
value
- wait(s):s-1
- wait操作:申请资源且可能阻塞自己(s<0)
l Signal operation increments semaphore value
- signal(s):s+1
- signal操作:释放资源并唤醒阻塞进程(s≤0)T y p e s o f S e m a p h o r e s
l General Semaphore (通用信号量)
§ 通用信号量是记录型,其中一个域为整型,另一个域
为队列,其元素为等待该信号量的阻塞进程(FIFO)
l Binary Semaphore (二进制信号量)G e n e r a l S e m a p h o r e
type semaphore = record
count : integer;
queue : list of process
end;
var s: semaphore;w a i t / s i g n a l O p e r a t i o n s
type semaphore = record
count : integer;
queue : list of process
end;
var s: semaphore;
signal(s):
wait(s):
s.count:= s.count + 1;
s.count := s.count – 1;
if s.count ≤ 0
if s.count < 0
then begin
then begin
wakeup the first P;
block P;
remove the P from
insert P into s.queue
s.queue;
;
end;
end;信号量的类型
l信号量分为:互斥信号量和资源信号量。
l互斥信号量用于申请或释放资源的使用权,常初始化为1。
l资源信号量用于申请或归还资源,可以初始化为大于1的正
整数,表示系统中某类资源的可用个数。
lwait操作用于申请资源(或使用权),进程执行wait原语
时,可能会阻塞自己;
lsignal操作用于释放资源(或归还资源使用权),进程执
行signal原语时,有责任唤醒一个阻塞进程。M u t u a l E x c l u s i o n : S e m a p h o r e s
信号量的意义
1. 互斥信号量:申请/释放使用权,常初始化为1
2. 资源信号量:申请/归还资源,资源信号量可以初始化为一个正整数(表示系
统中某类资源的可用个数),s.count的意义为:
s.count≥0:表示还可执行wait(s)而不会阻塞的进程数(可用资源数)
s.count﹤0:表示s.queue队列中阻塞进程的个数(被阻塞进程数)s . c o u n t 的 取 值 范 围
l 当仅有两个并发进程共享临界资源时,互斥信号量仅能取值0、1、-1。
其中,
- s.count=1,表示无进程进入临界区
- s.count=0,表示已有一个进程进入临界区
- s.count= - 1,则表示已有一进程正在等待进入
临界区
l 当用s来实现n个进程的互斥时,s.count 的取值范围为1~-(n-1)l 操作系统内核以系统调用形式提供wait和signal原语,应用程序通过该
系统调用实现进程间的互斥。
l 工程实践证明,利用信号量方法实现进程互斥是高效的,一直被广泛采
用。P r o d u c e r / C o n s u m e r P r o b l e m
l One or more producers are generating data and placing data in a buffer.
l A single consumer is taking items out of the buffer one at time.
l Only one producer or consumer may access the buffer at any one time.任务及要求
1. buffer不能并行操作(互斥),即某时刻只允许一个实体(producer
or consumer)访问buffer.
2. 控制producer and consumer同步读/写buffer,即不能向满buffer
写数据;不能在空buffer中取数据 .1 2 3 4 5 6 7 8
n
out in
( a
1 2 3 4 )5 6 7 8
n
in out
( b
)
其中,in表示存数据位置,out表示取数据位置
:被占用单元 , :空存储单元
图2.35 生产者/消费者循环使用缓冲区?
不控制生产者/消费者
l指针in和out初始化指向缓冲区的第一个存储单元。
l生产者通过in指针向存储单元存放数据,一次存放一条
数据,且in指针向后移一个位置。
l消费者从缓冲区中逐条取走数据,一次取一条数据,相
应的存储单元变为“空”。每取走一条数据,out指针向
后移一个存储单元位置。
l试想,如果不控制生产者与消费者,将会产生什么结果?生产者/消费者必须互斥
l 生产者和消费者可能同时进入缓冲区,甚至可能
同时读/写一个存储单元,将导致执行结果不确定。
l 这显然是不允许的。必须使生产者和消费者互斥
进入缓冲区。即,某时刻只允许一个实体(生产
者或消费者)访问缓冲区,生产者互斥消费者和
其它任何生产者。生产者/消费者必须同步
生产者不能向满缓冲区写数据,消费者也不能在
空缓冲区中取数据,即生产者与消费者必须同步。生产一条数据
是 否 有 数 无 阻塞
阻塞
据单元 等待资源
等待资源
无
有 被 唤
是否有空 被唤醒
否 醒
存储单元 是否
可用
有
阻塞
等待使用权
是否 否 是
阻塞
可用
等待使用权 取一条数据
被 唤
是
醒
被 唤
存入一条数据 醒 归 还 使 用
权
归还使用权 空单元加1
唤醒一个生产者
数据单元加1 消费数据
唤醒一个消费者
(b) 消费者
(a) 生产
者 图2.36 生产者/消费者执行流程图利用信号量实现生产者/消费者同步与互斥
program producer_consumer;
const sizeofbuffer =…; /* 缓冲区大小 */
var s: semaphore(:= 1); /* 互斥信号量s,初始化为1 */
n : semaphore(:= 0); /* 资源信号量n,数据单元,初始化为0 */
e : semaphore(:= sizeofbuffer); /* 资源信号量e,空存储单元 */
procedure producer ; procedure consumer ;
begin begin
repeat repeat
生产一条数据; wait(n);
wait(e); wait(s);
wait(s); 取一条数据
;
存入一条数据; signal(s);
signal(s); signal(e);
signal(n); 消费数
据;
forever forever
end; end;利用信号量实现生产者/消费者同步与互斥 (续)
begin /* 主程序 */
parbegin
producer ; consumer ;
parend
end.
图2.37 利用信号量实现生产者/消费者同步与互斥复杂生产-消费问题
桌上有一个盘子,每次只能放入一个水果,爸爸专门向盘子放入苹果,妈妈只向盘子放入橘
子,儿子只吃盘子里的橘子,女儿只吃盘子里的苹果,当盘子中有自己需要的水果时,女儿
或儿子可以从盘子中取出吃掉注意
1. 进程应该先申请资源信号量,再申请互斥信号量,顺序
不能颠倒。
2. 对任何信号量的wait与signal操作必须配对。同一进
程中的多对wait与signal语句只能嵌套,不能交叉。
3. 对同一个信号量的wait与signal可以不在同一个进程
中。
4. wait与signal语句不能颠倒顺序,wait语句一定先于
signal语句。R e a d e r s / W r i t e r s P r o b l e m
l Any number of readers may simultaneously read the file.
l Only one writer at a time may write to the file.
l If a writer is writing to the file, no reader may read it.R e a d e r s / W r i t e r s P r o b l e m
可用于解决多个进程共享一个数据区(文件、内存区、一组寄存
器等),其中若干读进程只能读数据,若干写进程只能写数据等实际问
题。R e a d e r s / W r i t e r s P r o b l e m ( R e a d e r s h a v e
p r i o r i t y )
l Readers have priority: 指一旦有读者正在读数据,允许多个读者同
时进入读数据,只有当全部读者退出,才允许写者进入写数据。
Writers are subject to starvation
-Readers/Writers Problem (Readers have priority
)
program readers_writers;
const readcount: integer; /* 统计读者个数 */
var x,wsem: semaphore(:= 1); /* 互斥信号量,初始化为1 */
procedure reader ; procedure writer;
begin
begin repeat
repeat wait(wsem);
写数据;
wait(x); signal(wsem);
forever
readcount : = readcount + 1; e n d ;
if readcount = 1 then wait (wsem);
signal(x);
begin /* 主程序 */
读数据; readcount := 0;
parbegin
reader; writer ;
wait(x);
parend
readcount : = readcount - 1;
end.
if readcount = 0 then signal(wsem);
signal(x);
forever
end;( W r i t e r s h a v e
R e a d e r s / W r i t e r s P r o b l e m
p r i o r i t y )
Writers have priority: 指只要有一个writer申请写数据,则不
再允许新的reader进入读数据program readers_writers;
const readcount ,writecount: integer;
var x,y,z,rsem,wsem: semaphore(:= 1);
procedure reader ;
procedure writer;
begin
begin
repeat
repeat
wait(z);
wait(y);
wait(rsem);
writecount := writecount + 1;
wait(x);
if writecount = 1 then wait
readcount : = readcount + 1;
(rsem);
if readcount = 1 then wait (wsem);
signal(y);
signal(x);
wait(wsem);
signal(rsem);
写数据;
signal(z);
signal(wsem);
读数据;
wait(y);
wait(x);
writecount := writecount - 1;
readcount : = readcount - 1;
if writecount = 0 then signal
if readcount = 0 then signal(wsem);
(rsem);
signal(x);
signal(y);
forever
forever
end;
end;(Writers have
Readers/Writers Problem
priority)
begin /* 主程序 */
readcount := 0; writecount := 0;
parbegin
reader; writer ;
parend
end.吸烟者问题
设有3个抽烟进程,一个供应进程,每个抽烟者不停地生产烟并抽掉它,但要生产并抽掉一支烟需
要三种材料,烟草、纸、胶水。三个抽烟进程分别拥有烟草、纸、胶水。但供应者每次只能提供
两种材料,拥有剩余资源的那个抽烟者可以取走材料并抽掉它,然后给供应者一个信号,此时供
应者就将另两种材料放在桌上,使得三个抽烟者轮流抽烟,如此循环S u m m a r y o f M u t u a l E x c l u s i o n
1. 利用wait、signal原语对Semaphore互斥操作实现,powerful and
flexible
2. 可用软件方法实现互斥,如Dekker 算法、Peterson算法等(但增
加处理负荷)
3. 可用硬件或固件方法实现互斥,如屏蔽中断、Test and Set指令等
(属于可接受的忙等)管程A p p r o a c h e s o f M u t u a l E x c l u s i o n
l Software Approaches
l Hardware Support
l Semaphores
l Monitors
l Message PassingMonitor(管程)——面向对象方法
l用信号量实现互斥,编程容易出错(wait、signal的出
现顺序和位置非常重要)
lSupport at Programming-language level
l管 程 是 用 并 发 p a s c a l 、 p a s c a l p l u s 、 M o d u l a - 2 、
Modula-3等语言编写的程序,现在已形成了许多库函数。
管程可以锁定任何对象,如链表或链表的元素等。
l用管程实现互斥比用信号量实现互斥,更简单、方便M o n i t o r s
l Monitor is a software module,由若干过程、局部于管程的数据、
初始化语句(组)组成
l Chief characteristics
§ Local data variables are accessible only by the monitor.
§ Process enters monitor by invoking one of its procedures.
§ Only one process may be executing in the monitor at a time.A p p r o a c h e s o f M u t u a l E x c l u s i o n
l Software Approaches
l Hardware Support
l Semaphores
l Monitors
l Message PassingM e s s a g e P a s s i n g
l Enforce mutual exclusion
l Exchange information
send (destination, message)
receive (source, message)S y n c h r o n i z a t i o n
l Sender and receiver may or may not be blocked (waiting for
message).
l Blocking send, blocking receive
§ Both sender and receiver are blocked until message is delivered.
§ Called a rendezvous(紧密同步,汇合)S y n c h r o n i z a t i o n
l Nonblocking send, blocking receive
§ Sender continues processing such as sending messages as quickly
as possible.
§ Receiver is blocked until the requested message arrives.
l Nonblocking send, nonblocking receive
§ Neither party is required to waitA d d r e s s i n g ( 寻 址 )
l Direct addressing
§ Send primitive includes a specific identifier of the destination
process.
§ Receive primitive could know ahead of time which process a
message is expected.
§ Receive primitive could use source parameter to return a value
when the receive operation has been performed.A d d r e s s i n g
l Indirect addressing
● messages are sent to a shared data structure consisting of queues.
mailboxes
● queues are called .
● one process sends a message to the mailbox and the other process picks up the
message from the mailbox.M e s s a g e F o r m a tM e s s a g e P a s s i n g ( M u t u a l
E x c l u s i o n )
l 若采用
l 多个进程共享邮箱mutex。若进程申请进入临界区,首先申请从mutex邮箱中接收
一条消息。若邮箱空,则该进程阻塞;若进程收到邮箱中的消息,则进入临界区,
执行完毕退出,并将该消息放回邮箱mutex。该消息as a token在进程间传递。利用消息传递实现互斥的通用模式
program mutualexclusion;
const n=…; /* 进程数 */
procedure P(i:integer);
var msg:message;
begin
repeat
receive(mutex,msg); /* 从邮箱接收一条
消息 */
<临界区>;
send(mutex,msg); /* 将消息发回到邮
箱 */
<其余部分>
forever begin /* 主程序 */
end; create_mailbox(mutex); /* 创建邮箱 */
send(mutex,null); /* 初始化,向邮箱发
送一条空消息 */
parbegin
P(1);
P(2);
…
P(n)
parend
end.M e s s a g e P a s s i n g ( P r o d u c e r / C o n s u m e r P r o b l e m )
l 解决有限buffer Producer/Consumer Problem
l 设两个邮箱:
§ Mayconsume: Producer存放数据,供Consumer取
走(即buffer数据区)
§ Mayproduce:存放空消息的buffer空间program mutualexclusion; procedure consumer;
const var cmsg:message;
capacity =…; /* 消息缓冲区大小 begin
*/ while true do
null = …; /* 空消息 */ begin
procedure producer; receive(mayconsume,cmsg);
var pmsg:message; consume(cmsg);
begin send(mayproduce,null);
while true do end
begin end;
receive(mayproduce,pmsg);
pmsg := produce;
send(mayconsume,pmsg); b e gin /* 主程序 */
end create_mailbox(mayproduce);
end; create_mailbox(mayconsume);
f o r i = 1 t o c a p a c i t y d o
send(mayproduce,null);
parbegin
producer;
consumer;
parend
end.