操作系统-第2章-进程与线程_第1页
操作系统-第2章-进程与线程_第2页
操作系统-第2章-进程与线程_第3页
操作系统-第2章-进程与线程_第4页
操作系统-第2章-进程与线程_第5页
已阅读5页,还剩217页未读, 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

操作系统

第二章进程与线程

内容

基础:进程描述及控制

■■避免:死锁与饥饿

・・解决:几个经典问题

■关于:进程通信

。策略:进程调度

2

62.1ProcessDescriptionand

Control

Learningobjectiv

BytheendofthisIcctureyoushouIdbeabIcto

•ExpIainwhat5sProcess,SwappingandThread

•掌握分析进程的结构,PCB,Processimage(进程映像)

•描述进程的基本状态及转换规则与原因

•区别进程的挂起与阻塞状态

•理解OS内核的主要功能

•理解ProcessControIPrimitives(原语)

・区别ProcessSwitchingvs.ModeSwitching

•区别Processvs.Thread

MajorRequirementsofanOperating

System

•InterleavetheexecutionofseveraprocessestomaximizeprocessorutiIization

whiIeprovidingreasonabIeresponsetime

•AIlocateresourcestoprocesses

•Supportinterprocesscommunicationandusercreationofprocesses

程序的执行顺序

•程序顺序执行

■程序顺序执行时的特征:顺序性、封闭性、可再现性

•程序并发执行

■程序并发执行时的特征:间断性、非封闭性、不可再现性

•程序并发执行条件(Bernstein条件)

■R(P1)nW(P2)UW(P1)HR(P2)UW(P1)HW(P2)={}

Process

•Alsocalledatask

•ExecutionofanindividuaIprogram

■进程是程序在一个数据集合上的运行过程,是系统进行资源分配和调度的

一个独立单位

■进程是可并发执行的程序在一个数据集合上的运行过程

•Canbetraced

■Iistthesequenceofinstructionsthatexecute

CharacteristicsofProcess

•Dynamic(动态性)

•Concurrency(并发性)

•Independent(独立性)

•Asynchronous(异步性)

ProcessStructure

•Programs

•Datas

•PCB(ProcessControIBlock进程控制块)

第8-9讲进程状态转换

ProcessStates

•进程的并发执行

•进程的2状态

•进程的5状态

•进程状态转换图

假设内存中有3个逆程A、B、C,他们的程序代码已全部装入内存。若A、

C两进程需要执行12条指令,B进程需要执行4条指令,且B进程执行到第

4条指令处必须等待I/Oo如何跟踪他们的执行过程?

Figure3.1Snapshot<jfExampleExecution(Figure3」

ntlitslrixrtkmCyck13

Dispatcher

•操作系统重要组件

•负责进程、线程、作业的调度与分配

•提供多种调度算法如先来先服务、短作业优先、时间片轮转等

•监测性能变化,如CPU使用率、10响应时间等

•Tiiheau

4|too

-1/0requ4ftlot

42。

io2

440log3

"e

麝

47”

"溜

»

5|12010

521201

33C・・M»4InnefPrw(♦“e•fflgw*3al

Two-StateProcessModeI

•Processmaybeinoneoftwostates

■Running(执行)

■Not-running(非执行)

Dispatch

Pause

(a)Statetransitiondl晔ram

Not-RunningProcessinaQueue

注:

•并非所有进程只要Not-running就处于ready(就绪),有的需要blocked(阻塞)等待I/O完成

•Not-running又可分为ready和blocked两种状态

AFive-StateModeI

•Running(运行)

•Ready(就绪)

•Blocked(阻塞)

•New(创建)

•Exit(终止)

•Running:占用处理机(单处理机环境中,某一时刻仅一个进程占用处理机)

•Ready:准备执行

•Blocked:等待某事件发生才能执行,如等待I/O完成等

•New:进程已经创建,但未被OS接纳为可执行进程

•Exit:因停止或取消,被OS从执行状态释放

Admit

Fivure36Five-StateProcessModel

•NulIfNew:新创建进程首先处于新状态

•NewfReady:OS接纳新状态进程为就绪进程

•Ready->Running:OS只能从就绪进程中选一个进程

执行

•RunningExit:执行状态的进程执行完毕,或被取

消,则转换为退出状态

•Running->Ready:分时系统中,时间片用完,或优

先级高的进程到来,将终止优先级低的进程的执行

•Running6Blocked:执行进程需要等待某事件发生。

通常因进程需要的系统调用不能立即完成,而阻塞

•Blocked-Ready:当阻塞进程等待的事件发生,就

转换为就绪状态

•Ready.Exit:某些系统允许父进程在任何情况下终

止其子进程。若一个父进程终止,其子孙进程都必须终

止。

•BlockedExit:同前

ProwM.A

Fi?ure3.6ProcessStatesforTrace<>fFi13J

UsingTwoQueues

Krnd,QIM-IM*

AdmitDh|Mtch

PFIKYWH-

Tlnw<Mit

E*ent1Queue

Kvcnl!Event1Wall

Occurs

E、cnt2Queue

Ewnl2Event2Wall

Occur.

E、cnl”Queue

>>cntn»cnlnWalt

Occurs

<blMuldnleblockedciueiws

Swapping(对换技术,交换技术)

将内存中暂时不能运行的进程,或暂时不用的数据和程序,Swapping-out到

外存,以腾出足够的内存空间,把已具备运行条件的进程,或进程所需要的数

据和程序,Swapping-in内存。

Swapping(对换技术,交换技术)

note

应该保证进程执行时间比交换时间长

交换空间通常作为磁盘的一整块,且独立于文件系统

普通的交换技术一般很少使用,交换技术的一些变体任然在UNIX等系统中使用

SuspendedProcesses

•ProcessorisfasterthanI/OsoaIIprocessescouIdbe

waitingforI/O

•Swaptheseprocessestodisktofreeupmorememory

•Blockedstatebecomessuspendstatev/henswappedtodisk

ReasonsforProcessSuspension

SwappingTheoperatingsystemneedstoreleasesufficientmain

memorytobringinaprocessthatisreadytoexecute

OtherOSreasonTheoperatingsystemmaysuspendabackgroundorutility

processoraprocessthatissuspectedofcausingaproblem

InteractiveuserrequestAusermaywishtosuspendexecutionofaprogramfor

purposesofdebuggingorinconnectionwiththeuseofa

resource

TimingAprocessmaybeexecutedperiodically(eg.an

accountingorsystemmonitoringprocess)andmaybe

suspendedwhilewaitingforthenexttimeinterval

ParentprocessrequestAparentprocessmaywishtosuspendexecutionofa

descendenttoexamineormodifythesuspendedprocess,or

tocoordinatetheactivityofvariousdescendents

被挂起进程的特征

•不能立即执行

•可能是等待某事件发生。若是,则阻塞条件独立于挂起条件,即使

阻塞事件发生,该进程也不能执行

•使之挂起的进程为:自身、其父进程、OS

•只有挂起它的进程才能使之由挂起状态转换为其他状态

Suspendvs.BIocked(挂起与阻塞)

问题

1•是否只能挂起阻塞进程?

2•如何激活一个挂起进程?

Suspenvs.BIocked

d区分两个概念:

•?进程是否等待事件,阻塞与否

?进程是否被换出内存,挂起与否

4种状态组合:

•Ready:进程在内存,准备执行

Blocked:进程在内存,等待事件

Ready,Suspend:进程在外存,只要调入内存

即可执行

Blocked,Suspend:进程在外存,等待事件

注:

处理机可调度执行的进程有两种:

•新创建的进程

•或换入一个以前挂起的进程

通常为避免增加系统负载,系统会换入一个以前挂起的进程执行。

OneSuspendState

Admit

NewReady

Suspend

SuspendBlocked

此方案存在问题!

Twonewstates

—Blocked,suspend

—Ready,suspend

TwoSuspendStates

Acthate

Blnckd/

BUI

Stipend

(b)WithTwoSuspendStates

具有挂起状态的进程状态转换

•BlockedBlocked.Suspend:OS通常将阻塞进程换出,

以腾出内存空间

•BIocked,Suspend.Ready,Suspend:当BIocked,

Suspend进程等待的事件发生时,可以将其转换为Ready,

Suspend

•Ready,SuspendReady:OS需要调入一个进程执行时

•ReadyReady,Suspend:一般,OS挂起阻塞进程。但有

时也会挂起就绪进程,释放足够的内存空间

•NewReady,Suspend(NewReady):新进程创建后,可

以插入到Ready队列或Ready,Suspend队列。若无足够的内

存分配给新进程,则需要NewReady,Suspend

具有挂起状态的进程状态转换(续)

•Blocked,SuspendBlocked:当BIocked,Suspend队列中有一个进程的阻塞事

件可能会很快发生,则可将一个Blocked,Suspend进程换入内存,变为Blocked

•RunningReady,Suspend:当执行进程的时间片用完时,会转换为Ready。

或,一个高优先级的Blocked,Suspend进程正好变为非阻塞状态,OS可以将执

行进程转换为Ready,Suspend状态

•AIIExit;通常,RunningExito但某些OS中,父进程可以终止其子进程,

使任何状态的进程都可转换为退出状态

ProcessDescription

?问题:

OS如何感知进程、控制进程及其所用的系统资源?

p〃

Virtiuil

Mem«y

ComfMitrr

Resources

3.9Prwessesa»dResources(reMMirceadkxrationat<HM?snapshotintime)

OperatingSystemControlStructures

•Informationaboutthecurrentstatusofeachprocessand

resource

•Tablesareconstructedforeachentitytheoperating

systemmanages

一MemoryTables

-I/OTables

FiIeTables

ProcesTable

Fimirc3.10Genera]Structure*OiM*ratiiwSystemControlTnNc

MemoryTables

•AIlocationofmainmemo-ytoprocesses.

•AIlocationofsecondarymemorytoprocesses.

•Protectionattributesforaccesstosharedmemoryregions.

•InformalionneededtomanagevirtuaImemory(虚拟存储)

I/OTables

•I/OdeviceisavailabIeorassigned.

•Statusof1/0operation.

•Locationinmainmemorybeingusedasthesourceor

destinationofthe1/0transfer.

FiIeTables

•Existenceoffiles.

•Locationonsecondarymemory.

•CurrentStatus.

•Attributes.

•Some!imesthisinformationismaintainedbyafiIe-managementsystem.

ProcessTabIe

•Whereprocessislocated.

•Attributesnecessaryforitsmanagement.

•ProcessID

•Processstate

•Locationinmemory

ProcessLocation

•ProcessincIudessetofprogramstobeexecuted.

•DatalocationsforIocaIandglobaIvariables.

•Anydefinedconstants.

•Stack.

•ProcesscontroIbIock(PCB)

•CoIlectionofattributes.

•Processimage(进程映像)

•CoIlectionofprogram,data,stack,andattributes.

Processimage

•UserData

•UserProgram

•SystemStack:存放系统及过程调用地址、参数

•ProcessControIBlock(PCB):OS感知进程、控制进程的数据结构

ProcessControIBlock

•简称PCB:是OS控制和管理进程时所用的基本数据结构

•作用:PCB是相关进程存在于系统中的唯一标志;系统根据PCB而感知相关

进程的存在。

・内容:通常情况下,PCB包含Identifiers(标识)、状态、控制、指针等

多种信息。

ProcessControIBlock(PCB)

•Processidentification

•Identifiers

•Identifierofthisprocess(进程ID)

•Identifieroftheprocessthatcreated

thisprocess(parentprocess)(父进程ID)

•Useridentifier(用户ID)

ProcessControIBlock

•ProcessorStateInformation

■User-VisibIeRegisters(用户可见寄存器)

•Auser-visibleregisterisonethatmaybereferencedbymeans

ofthemachineIanguagethattheprocessorexecutes.

•Typically,therearefrom8to32oftheseregisters,although

someRISCimplementationshaveover100.

ProcessControIBlock

•ProcessorStateInformation

•ControIandStatusRegisters

Thereareavarietyofprocessorregistersthatareemployedto

controItheoperationoftheprocessor.Theseinclude

•Programcounter:Containstheaddressofthe

nextinstructiontobefetched.

•Conditioncodes:ResuItofthemostrecent

arithmeticorlogicaIoperation(e.g.rsign,

zero,carry,equaI,overflow).

•Statusinformation:Includesinterrupt

enabled/disabledflags,executionmode.

ProcessControIBlock

•ProcessorStateInformation

•StackPointers

•Eachprocesshasoneormorelast-in-first-out(LIFO)

systemstacksassociatedwithit.

•AstackisusedtostoreparametersandcaIIing

addressesforprocedureandsystemcaIIs.

•Thestackpointerpointstothetopofthestack.

ProcessControIBlock

•ProcessControlInforma11on

•ScheduIingandStateInformation

・Processstate:definesthereadinessofthe

processtobescheduledforexecution(e.g.,

running,ready,waiting,haIted).

•Priority:OneormorefieIdsmaybeusedto

describethescheduIingpriorityofthe

process.

•Scheduling-relatedinformation:ThiswiII

dependonthescheduIingaIgorithmused.

•Event:Identityofeventtheprocessis

awaitingbeforeitcanberesumed

ProcessControIBlock

•ProcessControIInformation

•DataStructuring

•AprocessmaybeIinkedtootherprocess

inaqueue,ring,orsomeotherstructure.

•Aprocessmayexhibitaparent-chiId

(creator-created)reIationshipwith

anotherprocess.

•TheprocesscontroIblockmaycontain

pointerstootherprocessestosupport

thesestructures.

ProcessControIBlock

•ProcessControIInformation

•IntorprocessCommunication

•Variousflags,signaIs,andmessagesmaybeassociated

withcommunicationbetweentwoindependentprocesses.

•ProcessPrivileges

•Processesaregrantedprivilegesintermsofthememory

thatmaybeaccessedandthetypesofinstructionsthat

maybeexecuted.

ProcessControIBlock

•ProcessControIInformation

•MemoryManagement

•Thissectionmayincludepointerstosegment

and/orpagetablesthatdescribethevirtuaI

memoryassignedtothisprocess.

•ResourceOwnershipandUtiIization

•ResourcescontroIledbytheprocessmaybe

indicatedysuchasopenedfiles.Ahistory

ofutiIizationoftheprocessororother

resourcesmayaIsobeincluded;this

informationmaybeneededbythescheduIer.

ProcessControIBlock

Pnxr^

kknlinoiliimkknllfk?atk«iklrntlfkjitlim

1PFWTM%

FrucnaurStaleFroreMTStaleFruce»oStaleL<

InformationInformationInfurmatiuafBlock

Prncf('untruiFrwe*CunlruiC<jolrt4

InhirmilliMiInTormnllimInhirmatkm

[RrStockl«erSUK<txrsuct

FrhateIwrFrhateIwFfivateIf

AcklreviSpacrAcklFMSpacrAckirmSpore

<Fru(*ramNDaUi»(Prufu-an*^Dalai<Pruuram.DaUi

ShftrcdActinoSharedAdrtmftSharedAddrvw

SpaceSpaceSpace

Pnwv^1FnrKVM2PFIKV^A.

Figure3.12txerPrixTe-Memory

TypicalFunctionofanOSKernel(资源管理功能)

•ProcessManagement:进程创建和终止、调度、状态转换、同步和通

信、管理PCB

•MemoryManagement:为进程分配地址空间、对换、段/页管理

•I/OManagement:缓存管理、为进程分配I/O通道和设备

TypicalFunctionofanOSKernel(支撑功能)

•InterrupthandIing(中断处理)

•Timing(时钟管理)

•Primitive(原语):AtomicOperation

•Accounting(统计)

•Monitoring(监测)

ProcessControIPrimitives(原语)

•ProcessSwitch,进程切换

•CreateandTerminate,创建与终止

•BlockandWakeup,阻塞与唤醒

•SuspendandActivate,挂起与激活

WhentoSwitchaProcess

•Clockiinterrupt

•processhasexecutedforthemaximumaIlowabIetimesIice

(时间片)

•I/Ointerrupt

•MemoryfauIt(存储访问失效)

•memoryaddressisinvirtuaImemorysoitmustbebrought

intomainmemory

WhentoSwitchaProcess

•Trap(陷阱)

•erroroccurred

•maycauseprocesstobemovedtoExitstate

•SupervisorcaII(管理程序调入)

•suchasfiIeopen

ChangeofProcessState

•SavecontextofprocessorincIudingprogramcounterandotner

registers

•UpdatethePCBoftheprocessthatiscurrentlyrunning

•MovePCBtoappropriatequeue-ready,bIocked

•Selectanotherprocessforexecution

ChangeofProcessState

•UpdatethePCBoftheprocessselected

•Updatememory-managementdatastructures

•Restorecontextoftheselectedprocess

ProcessSwitchingvs.Mode

Switching

•ProcessSwitch,是作用于进程之间的一种操作。

当分派程序收回当前进程的CPU并准备把它分派

给某个就绪进程时,该操作将被引用。

•ModeSwitch,是进程内部所引用的一种操作。当

进程映像所包含的程序引用核心子系统所提供的

系统调用时,该操作将被引用。

ProcessGreation

•Submissionofabatchjob

•UserIogson

•Createdtoprovideaservicesuchasprint

•Processcreatesanotherprocess

ProcessGreation(creat。原语,步

骤)

1.为进程分配一个唯一标识号ID:主进程表中增加一个新的表项

2•为进程分配空间:用户地址空间、用户栈空间、PCB空间。若

共享已有空间,则应建立相应的链接。

3.初始化PCB:进程标识、处理机状态信息、进程状态

4.建立链接:若调度队列是链表,则将新进程插入到就绪或(就

绪,挂起)链表

5.建立或扩展其他数据结构

ProcessTermination(终止)

•BatchjobissuesHalt\nstruction

•Userlogsoff

•Quit(退出)anappIication

•ErrorandfauItconditions

ReasonsforProcessTermination

•NormaIcompletion,正常结束

•TimeIimitexceeded,超时终止,执行时间超过预计时间

•MemoryunavaiIable,内存不足,无法为进程分配所需的内存空间

•Boundsviolation,越界访问

•Protectionerror,企图使用未允许用的数据,或操作方式错

•Arithmeticerror,计算错,如除零,或企图存储硬件允许的最大数

•Timeoverrun,超时等待某事件发生

ReasonsforProcessTermination

•I/Ofailure,如找不到文件或多次重试仍无法读写文件,或无效操作

•InvaIidinstruction,企图执行不存在的指令

•PriviIegedinstruction,企图执行特权指令

•Datamisuse,数据类型不符,或未初始化

•Operatingsystemintervention,操作员或OS干预,如发生死锁的时候

•Parentterminates,sochiIdprocessesterminate

•Parentrequest

ProcessTermination(destroy。原语,

步骤)

1.根据被终止进程的标识符ID,找到其PCB,读出该进程的状态;

2.若该进程为执行状态,则终止其执行,调度新进程执行;

3.若该进程有子孙进程,则立即终止其所有子孙进程

4.将该进程的全部资源,或归还给其父进程,或归还给系统

5.将被终止进程(的PCB)从所在的队列中移出,等待其它程序来

搜集信息

ProcessBlockandWakeup(阻塞的原

因)

•请求系统服务

•启动某种操作:如I/O

・新数据尚未到达

・无新工作可做

ProcessBIockandWakeup(原语)

・阻塞原语block。

当出现阻塞事件,进程调用阻塞原语将自己阻塞。状态

变为“阻塞状态”,并进入相应事件的阻塞队列

•唤醒原语wakeup()

当阻塞进程期待的事件发生,有关进程调用唤醒原语,

将等待该事件的进程唤醒。状态变为Ready,插入就绪队列

ProcessBIockandWakeup(原语)

・挂起原语suspend()

当出现挂起事件,系统利用挂起原语将指定进程或阻

塞状态进程挂起。进程从内存换到外存,状态改变:

ReadyReady,Suspend;BIocked

Blocked,Suspend,插入相应队列

•激活原语active()

当激活事件发生,系统利用激活原语将指定进程激活。

进程从外存换入到内存,状态改变:Ready.Suspend

Ready;Blocked,SuspendBlocked,插入相应队列

Thread(线程)

•Anexecutionstate(running,ready,etc.)

•Savedthreadcontextwhennotrunning.

•Hasanexecutionstack.

•Someper-threadstaticstorageforIocaIvariables.

•Accesstothememoryandresourcesofitsprocess.

•aIIthreadsofaprocesssharethis.

Siiigle-llirviMiccIMultitlireaded

Prix^ssModelPr<>cv**sModel

Iser

Acklre**

Space

Eiuiire4.2SingleThreudvdandMultithreadedProcessMcxkls

BenefitsofThreads

•Takeslesstimetocreateanewthreadthana

process.

•Lesstimetoterminateathreadthanaprocess.

•Lesstimetoswitchbetweentwothreadswithin

thesameprocess.

•Sineethreadswithinthesameprocessshare

memoryandfiIes,theycancommunicatewith

eachotherwithoutinvokingthekerneI.

Threads

•SuspendingaprocessinvoIvessuspendingaIIthreadsof

theprocess

•sinceaIIthreadssharethesameaddressspace.

•Terminationofaprocess,terminatesaIIthreadswithin

theprocess.

MuItithreading

•OperatingsystemsupportsmuItipIethreadsof

executionwithinasingIeprocess.

•MS-DOSsupportsasingIethread.

•UNIXsupportsmuItipIeuserprocessesbutonIy

supportsonethreadperprocess.

•Windows2000,SoIaris,Linux,Mach,andOS/2

supportmuItipIethreads.

rmiltlpirpnmw*multiplepnCTM**

oneIhrvxlperpncwmultiplethrvachperpr1n

ImtriKtliiciIrace

Eiuure4.1TlirvmlsaixiPr«MessrsIANDE97

ThreadStates

•KeystatesforathreadRunning,Ready,Blocked.

•Operstionsassociatedwithachangeinthreadstate.

•Spawn(派生),Spawnanotherthread

•Block

•Unblock

•Finish

User-LeveThreads

•AIIthreadmanagementisdonebytheappIication.

•ThekerneIisnotawareoftheexistenceofthreads.

•描述此类线程的数据结构以及控制此类线程的原语在核外子系统中实现。

KerneI-LeveIThreads

•W2KrLinux,andOS/2areexamplesotthisapproach.

•Ker

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论