操作系统复习整理
2014-04-27 22:56
239 查看
操作系统概念,在计算机系统中的作用:
操作系统是计算机系统中的一个系统软件。一方面控制和管理计算机中的硬件和软件资源,合理的组织计算机工作流程,以使这些资源得到有效的利用。另一方面为用户提供一个功能强、使用方便的工作环境,从而在用户和计算机之间起到接口的作用。
可扩充硬件功能,为用户提供良好的运行环境
现代操作系统的基本特征是程序的并发执行、资源共享、操作的异步性
操作系统例题:
操作系统有多种类型:允许多个用户以交互方式使用计算机的操作系统,称为B;允许多用户将若干个作业提交给计算机系统集中处理的操作系统,称为A;在C的控制下,计算机系统能及时处理由过程控制反馈的数据,并作出响应;在IBM-PC机上的操作系统称为D。
A:批处理操作系统;B:分时操作系统;C:实时操作系统;D:微机操作系统;E:多处理机操作系统;F:分布式操作系统
多道批处理操作系统
http://baike.baidu.com/view/3078096.htm
现在的批处理系统主要指多道批处理系统,它通常用在以科学计算为主的大中型计算机上,由于多道程序能交替使用CPU,提高了CPU及其他系统资源的利用率,同时也提高了系统的效率。多道批处理系统的缺点是延长了作业的周转时间,用户不能进行直接干预,缺少交互性,不利于程序的开发与调试。
批处理系统的特点:
多道-在内存中同时存放多个作业,使之同时处于运行状态,这些作业共享CPU和外部设备等资源。
成批-用户和他的作业之间没有交互性。用户自己不能干预自己的作业的运行,发现作业错误不能及时改正。
作业平均周转时间较长
批处理系统的目的是提高系统吞吐量和资源的利用率。
适用于计算量大的成熟的作业。
分时系统:
http://baike.baidu.com/view/1295402.htm
分时系统具有多路性、交互性、“独占”性和及时性的特征。多路性指,同时有多个用户使用一台计算机,宏观上看是多个人同时使用一个CPU,微观上是多个人在不同时刻轮流使用CPU。交互性是指,用户根据系统响应结果进一步提出新请求(用户直接干预每一步)。“独占”性是指,用户感觉不到计算机为其他人服务,就像整个系统为他所独占。及时性指,系统对用户提出的请求及时响应。
我们可以很容易理解分时系统,它有如下特征:(1)同时性,计算机系统能被多个用户同时使用;(2)独立性:用户和用户之间都是独立操作系统的,在同时操作时并不会发生冲突,破坏,混淆等现象;(3)及时性:系统能以最快的速度将结果显示给用户;(4)交互作用性:用户能和电脑进行人机对话。
适用于计算量小的不成熟的作业。
系统调用SystemCall
指运行在用户态的程序向错做系统内核请求更高权限运行的服务,比如硬件相关的服务,创建并执行新进程。系统调用提供了用户程序与操作系统之间的接口。
特权指令:
常见的特权指令有以下几种:
(1)有关对I/O设备使用的指令如启动I/O设备指令、测试I/O设备工作状态和控制I/O设备动作的指令等。
(2)有关访问程序状态的指令如对程序状态字(PSW)的指令等。
(3)存取特殊寄存器指令如存取中断寄存器、时钟寄存器等指令。
(4)其他指令
举例:
清内存;关闭中断;从用户态转到监控态;修改界限寄存器指令
多线程编程的优点:(课本P112)
相应度高;
资源共享;
经济;
多处理器体系结构的利用;
多道程序设计(Multiprogramming)的主要目的:
充分利用处理机,减少处理机空闲时间;充分利用外围设备;
所谓多道程序设计指的是允许多个程序同时进入一个计算机系统的主存储器并启动进行计算的方法。也就是说,计算机内存中可以同时存放多道(两个以上相互独立的)程序,它们都处于开始和结束之间。从宏观上看是并行的,多道程序都处于运行中,并且都没有运行结束;从微观上看是串行的,各道程序轮流使用CPU,交替执行。
引入多道程序设计技术的根本目的是为了提高CPU的利用率,充分发挥计算机系统部件的并行性,现代计算机系统都采用了多道程序设计技术。
多道程序设计的基本特征:间断性、共享性、制约性。
多道程序主要优点如下:
(1)资源利用率高。由于内存中装入了多道程序,使它们共享资源,保持系统资源处于忙碌状态,从而使各种资源得以充分利用。
(2)系统吞吐量大。由于CPU和其它系统资源保持“忙碌”状态,而且仅当作业完成或运行不下去时才切换,系统开销小,所以吞吐量
多道程序(multiprogramming)和多重处理(multiprocessing)有何区别?
多道程序(multiprogramming)是作业之间自动调度执行、共享系统资源,并不是真正地同时执行多个作业;而多重处理(multiprocessing)系统配置多个CPU,能真正同时执行多道程序。要有效使用多重处理,必须采用多道程序设计技术,而多道程序设计原则上不一定要求多重处理系统的支持。
进程的特征
动态性:进程的实质是程序的一次执行过程,进程是动态产生,动态消亡的。
并发性:任何进程都可以同其他进程一起并发执行
独立性:进程是一个能独立运行的基本单位,同时也是系统分配资源和调度的独立单位;
异步性:由于进程间的相互制约,使进程具有执行的间断性,即进程按各自独立的、不可预知的速度向前推进
结构特征:进程由程序、数据和进程控制块三部分组成。
线程与进程的区别联系
进程与线程的关系:
(1)一个线程只能属于一个进程,而一个进程可以有多个线程,但至少有一个线程;
(2)资源分配给进程,同一进程的所有线程共享该进程的所有资源;
(3)处理机分给线程,即真正在处理机上运行的是线程;
(4)线程在执行过程中,需要协作同步。不同进程的线程间要利用消息通信的办法实现同步。
线程是指进程内的一个执行单位,也是进程内的可调度实体。
与进程的区别:
(1)调度:线程作为调度和分配的基本单位,进程作为拥有资源的基本单位;
(2)并发性:不仅进程之间可以并发执行,同一个进程的多个线程之间也可并发执行;
(3)拥有资源:进程是拥有资源的一个独立单位,线程不拥有系统资源,但可以访问隶属于进程的资源。
(4)系统开销:在创建或撤销进程时,由于系统都要为之分配和回收资源,导致系统的开销明显大于创建或撤销线程时的开销。但是进程有独立的地址空间,一个进程崩溃后,在保护模式下不会对其它进程产生影响,而线程只是一个进程中的不同执行路径。线程有自己的堆栈和局部变量,但线程之间没有独立的地址空间,一个线程死掉等于整个进程死掉,所以多进程的程序要比多线程的程序健壮,但在进程切换时,耗费资源较大,效率要差一些。
从进程演化出线程,最主要的目的就是更好的支持SMP(SymmetricMulti-Processing对称多处理结构)以及减小(进程/线程)上下文切换开销
进程可以分为系统进程和用户进程。凡是用于完成操作系统的各种功能的进程就是系统进程,它们就是处于运行状态下的操作系统本身;用户进程就是所有由你启动的进程。进程是操作系统进行资源分配的单位
根据操作系统内核是否对线程可感知,可以把线程分为内核线程和用户线程。
内核线程建立和销毁都是由操作系统负责、通过系统调用完成的,操作系统在调度时,参考各进程内的线程运行情况做出调度决定,如果一个进程中没有就绪态的线程,那么这个进程也不会被调度占用CPU。
和内核线程相对应的是用户线程,用户线程指不需要内核支持而在用户程序中实现的线程,其不依赖于操作系统核心,用户进程利用线程库提供创建、同步、调度和管理线程的函数来控制用户线程。用户线程多见于一些历史悠久的操作系统,例如Unix操作系统,不需要用户态/核心态切换,速度快,操作系统内核不知道多线程的存在,因此一个线程阻塞将使得整个进程(包括它的所有线程)阻塞。由于这里的处理器时间片分配是以进程为基本单位,所以每个线程执行的时间相对减少为了在操作系统中加入线程支持,采用了在用户空间增加运行库来实现线程,这些运行库被称为“线程包”,用户线程是不能被操作系统所感知的。
引入用户线程,具体而言,有以下四个方面的优势:
(1)可以在不支持线程的操作系统中实现。
(2)创建和销毁线程、线程切换代价等线程管理的代价比内核线程少得多。
(3)允许每个进程定制自己的调度算法,线程管理比较灵活。
(4)线程能够利用的表空间和堆栈空间比内核级线程多。
用户线程的缺点主要有以下两点:
(1)同一进程中只能同时有一个线程在运行,如果有一个线程使用了系统调用而阻塞,那么整个进程都会被挂起。
(2)页面失效也会产生类似的问题。
内核线程的优缺点刚好跟用户线程相反。实际上,操作系统可以使用混合的方式来实现线程。
并发性、同时性、并行性
并发性是指两个或多个事件在同一时间间隔内发生。
同时性是指两个或多个事件在同一时刻发生。
二者的概念:
幷发的实质是一个物理CPU(也可以多个物理CPU)在若干道程序之间多路复用,并发性是对有限物理资源强制行驶多用户共享以提高效率。并发性是关于软件过程分解成进程、线程并处理相关的效率、原子性、同步和调度问题。
实现幷发技术的关键之一是如何对系统内的多个活动(进程)进行切换。
并行性指的是两个或两个以上的事件或活动在同一时刻发生。在多道程序环境下,并行性使多个程序同一时刻可在不同CPU上同时执行。
并行性和并发性的区别:
并行的时间或者活动一定是并发的,但是反之并发的时间或者活动未必是并行的。并行性是并发性的特例,而并发性是并行性的拓展。
叙述抢占与非抢占调度策略之间的区别,解释为什么在分时系统中不可能使用严格的非抢占调度策略。
抢占调度策略允许中断一个正在执行的进程,并抢占他所占有的CPU,把CPU分配给另一个进程。非抢占策略确保一进城仅当它完成了自己当前所占用的CPU时间片后才释放CPU。
非抢占策略不适用于分时系统,因为他不能保证每个用户相似固定的时间间隔内共享CPU。非抢占调度策略允许程序无限期的运行下去,这样就厌恶了其他已提交作业的轮转时间(响应时间)
进程调度中"可抢占"和"非抢占"两种方式,哪一种系统的开销更大?为什么?
(1)可抢占式会引起系统的开销更大。
(2)可抢占式调度是严格保证任何时刻,让具有最高优先数(权)的进程占有处理机运行,因此增加了处理机调度的时机,引起为退出处理机的进程保留现场,为占有处理机的进程恢复现场等时间开销增大。
死锁:
死锁定义:指多个进程因竞争资源而造成的一种僵局,若无外力的作用,这些进程将永远不能再向前推进。
产生死锁的原因主要是:
(1)因为系统资源不足。
(2)进程运行推进的顺序不合适。
(3)资源分配不当等。
如果系统资源充足,进程的资源请求都能够得到满足,死锁出现的可能性就很低,否则就会因争夺有限的资源而陷入死锁。其次,进程运行推进顺序与速度不同,也可能产生死锁。
产生死锁的四个必要条件:
(1)互斥条件:一个资源每次只能被一个进程使用。
(2)请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
(3)不剥夺条件:进程已获得的资源,在末使用完之前,不能强行剥夺。
(4)循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。
这四个条件是死锁的必要条件,只要系统发生死锁,这些条件必然成立,而只要上述条件之一不满足,就不会发生死锁。
死锁的解除与预防:
理解了死锁的原因,尤其是产生死锁的四个必要条件,就可以最大可能地避免、预防和解除死锁。所以,在系统设计、进程调度等方面注意如何不让这四个必要条件成立,如何确定资源的合理分配算法,避免进程永久占据系统资源。此外,也要防止进程在处于等待状态的情况下占用资源。因此,对资源的分配要给予合理的规划。
处理死锁的策略
1、忽略该问题。例如鸵鸟算法,该算法可以应用在极少发生死锁的的情况下。为什么叫鸵鸟算法呢,因为传说中鸵鸟看到危险就把头埋在地底下,可能鸵鸟觉得看不到危险也就没危险了吧。跟掩耳盗铃有点像。
2、检测死锁并且恢复。
3、仔细地对资源进行动态分配,以避免死锁。
4、通过破除死锁四个必要条件之一,来防止死锁产生。
1.Whatisthedeadlock?
Answer:Asetofblockedprocesseseachholdingaresourceandwaitingtoacquirearesourceheldbyanotherprocessintheset.
Howtopreventthedeadlockoccurred?
Answer:Byensuringthatatleastoneoffourconditions(MutualExclusion,HoldandWait,NoPreemption,CircularWait)cannothold,wecanpreventtheoccurrenceofadeadlock.
Howtoavoidthedeadlockoccurred?
TouseSafetyAlgorithm:
IfasystemisinsafestateÞnodeadlocks.
IfasystemisinunsafestateÞpossibilityofdeadlock.
AvoidanceÞensurethatasystemwillneverenteranunsafestate.
读者-写者问题,令写者优先
https://en.wikipedia.org/wiki/Readers%E2%80%93writers_problem
wouldbefoolishforR2tojumpinimmediately,aheadofW;ifthathappenedoftenenough,Wwouldstarve.Instead,Wshould
startassoonaspossible.Thisisthemotivationforthesecondreaders-writersproblem,inwhichtheconstraintisaddedthatnowriter,onceaddedtothequeue,shallbekeptwaitinglongerthanabsolutelynecessary.Here,P()isforwaitand
V()isforsignal.Thisisalsocalledwriters-preference.
Asolutiontothewriters-preferencescenarioispresentedbelow:.[1]Inthis
code,thesemaphoremutex_1protectsthereadcountvariable,mutex_2protectsthewritecountvariable,themutex'r'protectsthereadingoperation,andthemutex'w'protectsthewritingoperation.
调度算法选择
我们如果为每一个作业只建立一个进程,则为了照顾短作业用户,应采用
B;;为照顾紧急作业用户,应采用E,为能实现人机交互作用应采用
C,而能使短作业,长作业及交互作业用户都比较满意时,应采用D
A:FCFS调度算法;B:短作业优先调度算法;C:时间片轮转法;D:多级反馈队列调度算法;E:基于优先权的剥夺调度算法;F:响应比优先算法。
临界区:
多个进程之间共享资源,这样的每个进程的代码段就成为临界区(一段代码)
理发师问题
TheSleeping-BarberProblem.Abarbershopconsistsofawaitingroomwithnchairsandabarberroomwithonebarberchair.Iftherearenocustomerstobeserved,thebarbergoestosleep.Ifacustomerentersthebarbershopandall
chairsareoccupied,thenthecustomerleavestheshop.Ifthebarberisbusybutchairsareavailable,thenthecustomersitsinoneofthefreechairs.Ifthebarberisasleep,thecustomerwakesupthebarber.Writeaprogramtocoordinatethebarberandthecustomers.
Answer:
(1)BarberShop.java
//ThisclassdefinestheBarberShopScenario.
//ThisscenarioallowsNcustomerstoenterit.
//Italsocontainsanumberofchairsthatallowthecustomerstowaitin.
publicclassBarberShop
{
privateintchairNum;
privateintbarber;
privateintchairState[];
staticfinalintFULL=-1;
staticfinalintEMPTY=0;
staticfinalintOCUPIED=1;
staticfinalintSLEEPING=2;
staticfinalintDONE=3;
staticfinalintWAITED=4;
/*============================================================
ConstructanewBarberShopscenarioforcustomerstogethaircutsat.SetthebarbershoptohaveNnumberofchairstowaitin.Thenmakeallthechairstobeinitiallyempty.Alsosetthebarbertobeasleepsothatwhenhisfirstcustomercomesinhecan
wakehimup.
@parampChairNumThenumberofwaitingchairsinthisbarbershop
==================================================================*/
publicBarberShop(intpChairNum)
{
chairNum=pChairNum;
chairState=newint[chairNum];
barber=SLEEPING;
//initializeeverychairinthewaitingroomtobeempty
for(inti=0;i<chairNum;i++)
chairState[i]=EMPTY;
}
/*============================================================
ThismethodiscalledwhenacustomerseesthattheBarberisbusy.Thismeansthatthecustomermustwaitforthebarber.Therefore,findachairinthewaitingroom.WhenthecustomerfindsachairtheysetitsstatetoOCUPIED(sothere'sonlyonecustomer
perchair)andreturntrue.Otherwise,therearenochairsavailablesoreturnfalse.
@parampCustomerThecustomerwantingtofindachairtowaitin.
@returnbooleanTrueifchairisfound;Falseotherwise.
============================================================*/
privatebooleanfindChair(intpCustomer)
{
//trytofindachairtowaitin
inttest=getFirstEmptyChair();
//ifbarbershopisfullreturnfalse
if(test==FULL)
returnfalse;
//otherwisesitdowninthischair
else
chairState[test]=OCUPIED;
returntrue;
}
/*============================================================
ThismethodiscalledbytheCustomerthreadtogetahaircut.IFthebarber'sasleepthenthecustomerwakeshimupandthecustomergetstheirhaircut.IFthebarber'salreadybusythenthecustomertriestofindachairtowaitin.However,ifthereare
nochairsandthebarbersbusy,thentheshopisfull,socustomerwillthenleave.Ifthebarber'sstateisnotsleepingorocupied,thenhecantakethecustomerimmediately.
Thissolutiondoesn'tpreventstarvationforthewaitingcustomers.IfAcustomerfinnalygetsnotifiedtoleavethewaitingstatetheywillbethenexthaircut.Ifanothercustomerenterstheshopatthesametime,thenthatcustomerwillalwayshavetowair
forexistingcustomerstobeserviced.
@paramcustomerThecustomerwantingtogetahaircut
@returnintThestateoftheBarberShopand/orbarber
===========================================================*/
publicsynchronizedintgetHairCut(intcustomer)
{
//ifthebarber'ssleeping,thenwakehimupandtellhimtogettowork
if(barber==SLEEPING)
{
barber=OCUPIED;
returnSLEEPING;
}
//thebarber'sbusytrytowaitforhiminthewaitingroom
elseif(barber==OCUPIED)
{
booleantest=findChair(customer);
//ifbarbershopisfullreturnfullandgetout.
if(test==false)
returnFULL;
else
{
//waitaslongasthebarberisbusy
while(barber==OCUPIED)
{
try{this.wait();}
catch(InterruptedExceptione)
{}
}
//waitingcustomerwillgettobethenexthaircutscheduled.Thereforethey
//standupandgiveuptheirchair.Thisiswhyachairgetsresettoempty.
for(inti=0;i<chairNum;i++)
{
if(chairState[i]==OCUPIED)
{
chairState[i]=EMPTY;
break;
}
}
//setbarbertoocupiedsincethiswaitingcustomerwillgetnexthaircut.
barber=OCUPIED;
returnWAITED;
}
}
//barber'sdone.Thiscustomercangettheirhaircutimmediately
else
{
barber=OCUPIED;
returnDONE;
}
}
/*============================================================
Thismethodiscalledwhenthecustomerhasrecievedtheirhaircutandtheyleavetheshop.Theyfirstchecktoseeifanyoneelseiswaitingintheshop.Ifthereisn'tanyone,thentheywerethelastcustomer.Thismeansthebarbermustgobacktosleep.
Otherwisepoeplearewaiting,sojustsetbarber'sstatetodone.Thennotifyanyonewaiting.
@paramcustomerThecustomerfinishedwithhaircutandleavingshop
@returnvoid
============================================================*/
publicsynchronizedvoidleaveBarberShop(intcustomer)
{
booleantest=isAnyoneWaiting();
if(test==true)
barber=DONE;
else
barber=SLEEPING;
//notifyonlyonewaitingcustomer(ifanyexist)
//thishelpsonperformanceoftheprogram.
notify();
}
/*============================================================
Findthefirstemptychairinthewaitingroomandreturnit.Ifnochairsarefoundthenallchairsareocupiedbyawaitingcustomer.
@returnintThenumberoftheemptychair;FULLotherwise
============================================================*/
privateintgetFirstEmptyChair()
{
//ifanemptychairisfoundreturnit
for(inti=0;i<chairNum;i++)
{
if(chairState[i]==EMPTY)
returni;
}
//allchairsareoccupiedsoreturnFULL
returnFULL;
}
/*============================================================
Testtoseeifthewaitingroomhasanycustomersinit.
@returnbooleanTrueiftherearecustomerswaiting;Falseifempty
============================================================*/
privatebooleanisAnyoneWaiting()
{
//seeifanyoneisinachairwaiting
for(inti=0;i<chairNum;i++)
{
if(chairState[i]==OCUPIED)
returntrue;
}
//couldn'tfindanyonewaiting
returnfalse;
}
}
(2)Customer.java
//Thisclasscreatesacustomerwhoiswantingahaircut.
//Oncethehaircutisreceivedthecustomerthenhasfinishedtheirtask
//andtheyhavetobere-instantiatediftheywantanotherhaircut.
importjava.util.*;
publicclassCustomerimplementsRunnable
{
privateBarberShopshop;
privateintcustomer;
privateintHAIRCUT_TIME=5;
//Constructanewcustomerwiththeiruniqueidentity
//andgivethemabarbershoptoenterfortheirhaircut.
//@parampCustomerThiscustomer'sidentifier.
//@parampShopThebarbershoptheywillgetahaircutin.
publicCustomer(intpCustomer,BarberShoppShop)
{
shop=pShop;
customer=pCustomer;
}
/**
*Therunmethodforthecustomerthreadtriestogetthecustomera
*haircut.
*/
publicvoidrun()
{
intsleeptime=(int)(HAIRCUT_TIME*Math.random());
System.out.println("ENTERINGSHOP:Customer["+customer+"]enteringbarbershopforhaircut.");
inttest=BarberShop.OCUPIED;
//testforthiscustomer'shaircutposibility
test=shop.getHairCut(customer);
//ifthebarberwasbusy,thenthiscustomerhaswaitedinthewaitingroom.
//Thiswaitingcustomerwillnowgetthenexthaircut.Enteringthreadswill
//havetowaitfortheexistingcustomerstobeserviced.Asfaraswhich
//waitingthreadwillgetservicednextisuptotheJVM.
if(test==BarberShop.WAITED)
System.out.println("Barber'sbusy:Customer["+customer+"]haswaitedandnowwantshaircut.");
//otherwise,nooneinbarbershop,wakeupbarberandgethaircut
elseif(test==BarberShop.SLEEPING)
System.out.println("Barber'sasleep:Customer["+customer+"]iswakinghimupandgettinghaircut.");
//thisbarbershopisfull.Thereforeleaveandneverreturn.
elseif(test==BarberShop.FULL)
{
System.out.println("BarberShopfull:Customer["+customer+"]isleavingshop.");
return;
}
//Barber'sreadytotakethiscustomerrightawayforahaircut.
else
System.out.println("HAIRCUT:Customer["+customer+"]isgettinghaircut.");
//customerisnowgettingtheirhaircutforanamountoftime
SleepUtilities.nap();
//haircutfinished.Leavetheshopandnotifyanyonewaiting.
System.out.println("LEAVINGSHOP:Customer["+customer+"]haircutfinished:leavingshop.");
shop.leaveBarberShop(customer);
}
}
(3)SleepUtilities.java
//Utilitiesforcausingathreadtosleep.
//Note,weshouldbehandlinginterruptedexceptions
//butchoosenottodosoforcodeclarity.
publicclassSleepUtilities
{
//NapbetweenzeroandNAP_TIMEseconds.
publicstaticvoidnap(){
nap(NAP_TIME);
}
//Napbetweenzeroanddurationseconds.
publicstaticvoidnap(intduration){
intsleeptime=(int)(NAP_TIME*Math.random());
try{Thread.sleep(sleeptime*1000);}
catch(InterruptedExceptione){}
}
privatestaticfinalintNAP_TIME=5;
}
(4)CreateBarberShopTest.java
//TestStubfortheBarberShop\Customerproblem.
//Thisclassaddscustomerstoaconstructedbarbershopindefinately.
publicclassCreateBarberShopTestimplementsRunnable
{
staticfinalprivateintWAIT_TIME=3;
staticpublicvoidmain(String[]args)
{
newThread(newCreateBarberShopTest()).start();
}
publicvoidrun()
{
//createthebarbershop
BarberShopnewShop=newBarberShop(15);
intcustomerID=1;
//addthespecifidnumberofthreadstoshop
while(customerID<=10000)
{
//addcustomerstothebarbershop
newThread(newCustomer(customerID,newShop)).start();
customerID++;
//waitthisamountoftimebeforeaddinganothercustomertoshop
SleepUtilities.nap();
}
}
}
操作系统是计算机系统中的一个系统软件。一方面控制和管理计算机中的硬件和软件资源,合理的组织计算机工作流程,以使这些资源得到有效的利用。另一方面为用户提供一个功能强、使用方便的工作环境,从而在用户和计算机之间起到接口的作用。
可扩充硬件功能,为用户提供良好的运行环境
现代操作系统的基本特征是程序的并发执行、资源共享、操作的异步性
操作系统例题:
操作系统有多种类型:允许多个用户以交互方式使用计算机的操作系统,称为B;允许多用户将若干个作业提交给计算机系统集中处理的操作系统,称为A;在C的控制下,计算机系统能及时处理由过程控制反馈的数据,并作出响应;在IBM-PC机上的操作系统称为D。
A:批处理操作系统;B:分时操作系统;C:实时操作系统;D:微机操作系统;E:多处理机操作系统;F:分布式操作系统
多道批处理操作系统
现在的
多道-在内存中同时存放多个作业,使之同时处于运行状态,这些作业共享CPU和
成批-用户和他的作业之间没有
作业平均周转时间较长
适用于计算量大的成熟的作业。
分时系统:
分时系统具有多路性、
我们可以很容易理解分时系统,它有如下特征:(1)同时性,计算机系统能被多个用户同时使用;(2)独立性:用户和用户之间都是独立操作系统的,在同时操作时并不会发生冲突,破坏,混淆等现象;(3)及时性:系统能以最快的速度将结果显示给用户;(4)交互作用性:用户能和电脑进行人机对话。
适用于计算量小的不成熟的作业。
系统调用SystemCall
指运行在用户态的程序向错做系统内核请求更高权限运行的服务,比如硬件相关的服务,创建并执行新进程。系统调用提供了用户程序与操作系统之间的接口。
特权指令:
常见的特权指令有以下几种:
(1)有关对I/O设备使用的指令如启动I/O设备指令、测试I/O设备工作状态和控制I/O设备动作的指令等。
(2)有关访问程序状态的指令如对
(3)存取特殊
(4)其他指令
举例:
清内存;关闭中断;从用户态转到监控态;修改界限寄存器指令
多线程编程的优点:(课本P112)
相应度高;
资源共享;
经济;
多处理器体系结构的利用;
多道程序设计(Multiprogramming)的主要目的:
充分利用处理机,减少处理机空闲时间;充分利用外围设备;
所谓多道程序设计指的是允许多个程序同时进入一个
引入
多道程序设计的基本特征:间断性、共享性、制约性。
多道程序主要优点如下:
(1)资源利用率高。由于内存中装入了多道程序,使它们共享资源,保持系统资源处于忙碌状态,从而使各种资源得以充分利用。
(2)系统吞吐量大。由于CPU和其它系统资源保持“忙碌”状态,而且仅当作业完成或运行不下去时才切换,系统开销小,所以吞吐量
多道程序(multiprogramming)和多重处理(multiprocessing)有何区别?
多道程序(multiprogramming)是作业之间自动调度执行、共享系统资源,并不是真正地同时执行多个作业;而多重处理(multiprocessing)系统配置多个CPU,能真正同时执行多道程序。要有效使用多重处理,必须采用多道程序设计技术,而多道程序设计原则上不一定要求多重处理系统的支持。
进程的特征
动态性:进程的实质是程序的一次执行过程,进程是动态产生,动态消亡的。
并发性:任何进程都可以同其他进程一起并发执行
独立性:进程是一个能独立运行的基本单位,同时也是系统分配资源和调度的独立单位;
异步性:由于进程间的相互制约,使进程具有执行的间断性,即进程按各自独立的、不可预知的速度向前推进
结构特征:进程由程序、数据和进程控制块三部分组成。
线程与进程的区别联系
进程与线程的关系:
(1)一个线程只能属于一个进程,而一个进程可以有多个线程,但至少有一个线程;
(2)资源分配给进程,同一进程的所有线程共享该进程的所有资源;
(3)处理机分给线程,即真正在处理机上运行的是线程;
(4)线程在执行过程中,需要协作同步。不同进程的线程间要利用消息通信的办法实现同步。
线程是指进程内的一个执行单位,也是进程内的可调度实体。
与进程的区别:
(1)调度:线程作为调度和分配的基本单位,进程作为拥有资源的基本单位;
(2)并发性:不仅进程之间可以并发执行,同一个进程的多个线程之间也可并发执行;
(3)拥有资源:进程是拥有资源的一个独立单位,线程不拥有系统资源,但可以访问隶属于进程的资源。
(4)系统开销:在创建或撤销进程时,由于系统都要为之分配和回收资源,导致系统的开销明显大于创建或撤销线程时的开销。但是进程有独立的地址空间,一个进程崩溃后,在保护模式下不会对其它进程产生影响,而线程只是一个进程中的不同执行路径。线程有自己的堆栈和局部变量,但线程之间没有独立的地址空间,一个线程死掉等于整个进程死掉,所以多进程的程序要比多线程的程序健壮,但在进程切换时,耗费资源较大,效率要差一些。
从进程演化出线程,最主要的目的就是更好的支持SMP(SymmetricMulti-Processing对称多处理结构)以及减小(进程/线程)上下文切换开销
进程可以分为系统进程和用户进程。凡是用于完成操作系统的各种功能的进程就是系统进程,它们就是处于运行状态下的
根据操作系统内核是否对线程可感知,可以把线程分为内核线程和用户线程。
内核线程建立和销毁都是由操作系统负责、通过系统调用完成的,操作系统在调度时,参考各进程内的线程运行情况做出调度决定,如果一个进程中没有就绪态的线程,那么这个进程也不会被调度占用CPU。
和内核线程相对应的是用户线程,用户线程指不需要内核支持而在用户程序中实现的线程,其不依赖于操作系统核心,用户进程利用线程库提供创建、同步、调度和管理线程的函数来控制用户线程。用户线程多见于一些历史悠久的操作系统,例如Unix操作系统,不需要用户态/核心态切换,速度快,操作系统内核不知道多线程的存在,因此一个线程阻塞将使得整个进程(包括它的所有线程)阻塞。由于这里的处理器时间片分配是以进程为基本单位,所以每个线程执行的时间相对减少为了在操作系统中加入线程支持,采用了在用户空间增加运行库来实现线程,这些运行库被称为“线程包”,用户线程是不能被操作系统所感知的。
引入用户线程,具体而言,有以下四个方面的优势:
(1)可以在不支持线程的操作系统中实现。
(2)创建和销毁线程、线程切换代价等线程管理的代价比内核线程少得多。
(3)允许每个进程定制自己的调度算法,线程管理比较灵活。
(4)线程能够利用的表空间和堆栈空间比内核级线程多。
用户线程的缺点主要有以下两点:
(1)同一进程中只能同时有一个线程在运行,如果有一个线程使用了系统调用而阻塞,那么整个进程都会被挂起。
(2)页面失效也会产生类似的问题。
内核线程的优缺点刚好跟用户线程相反。实际上,操作系统可以使用混合的方式来实现线程。
并发性、同时性、并行性
并发性是指两个或多个事件在同一时间间隔内发生。
二者的概念:
幷发的实质是一个物理CPU(也可以多个物理CPU)在若干道程序之间多路复用,并发性是对有限物理资源强制行驶多用户共享以提高效率。并发性是关于
实现幷发技术的关键之一是如何对系统内的多个活动(进程)进行切换。
并行的时间或者活动一定是并发的,但是反之并发的时间或者活动未必是并行的。
叙述抢占与非抢占调度策略之间的区别,解释为什么在分时系统中不可能使用严格的非抢占调度策略。
抢占调度策略允许中断一个正在执行的进程,并抢占他所占有的CPU,把CPU分配给另一个进程。非抢占策略确保一进城仅当它完成了自己当前所占用的CPU时间片后才释放CPU。
非抢占策略不适用于分时系统,因为他不能保证每个用户相似固定的时间间隔内共享CPU。非抢占调度策略允许程序无限期的运行下去,这样就厌恶了其他已提交作业的轮转时间(响应时间)
进程调度中"可抢占"和"非抢占"两种方式,哪一种系统的开销更大?为什么?
(1)可抢占式会引起系统的开销更大。
(2)可抢占式调度是严格保证任何时刻,让具有最高优先数(权)的进程占有处理机运行,因此增加了处理机调度的时机,引起为退出处理机的进程保留现场,为占有处理机的进程恢复现场等时间开销增大。
死锁:
死锁定义:指多个进程因竞争资源而造成的一种僵局,若无外力的作用,这些进程将永远不能再向前推进。
产生死锁的原因主要是:
(1)因为系统资源不足。
(2)进程运行推进的顺序不合适。
(3)资源分配不当等。
如果系统资源充足,进程的资源请求都能够得到满足,死锁出现的可能性就很低,否则就会因争夺有限的资源而陷入死锁。其次,进程运行推进顺序与速度不同,也可能产生死锁。
产生死锁的四个必要条件:
(1)互斥条件:一个资源每次只能被一个进程使用。
(2)请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
(3)不剥夺条件:进程已获得的资源,在末使用完之前,不能强行剥夺。
(4)循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。
这四个条件是死锁的必要条件,只要系统发生死锁,这些条件必然成立,而只要上述条件之一不满足,就不会发生死锁。
死锁的解除与预防:
理解了死锁的原因,尤其是产生死锁的四个必要条件,就可以最大可能地避免、预防和解除死锁。所以,在系统设计、进程调度等方面注意如何不让这四个必要条件成立,如何确定资源的合理分配算法,避免进程永久占据系统资源。此外,也要防止进程在处于等待状态的情况下占用资源。因此,对资源的分配要给予合理的规划。
处理死锁的策略
1、忽略该问题。例如鸵鸟算法,该算法可以应用在极少发生死锁的的情况下。为什么叫鸵鸟算法呢,因为传说中鸵鸟看到危险就把头埋在地底下,可能鸵鸟觉得看不到危险也就没危险了吧。跟掩耳盗铃有点像。
2、检测死锁并且恢复。
3、仔细地对资源进行动态分配,以避免死锁。
4、通过破除死锁四个必要条件之一,来防止死锁产生。
1.Whatisthedeadlock?
Answer:Asetofblockedprocesseseachholdingaresourceandwaitingtoacquirearesourceheldbyanotherprocessintheset.
Howtopreventthedeadlockoccurred?
Answer:Byensuringthatatleastoneoffourconditions(MutualExclusion,HoldandWait,NoPreemption,CircularWait)cannothold,wecanpreventtheoccurrenceofadeadlock.
Howtoavoidthedeadlockoccurred?
TouseSafetyAlgorithm:
IfasystemisinsafestateÞnodeadlocks.
IfasystemisinunsafestateÞpossibilityofdeadlock.
AvoidanceÞensurethatasystemwillneverenteranunsafestate.
读者-写者问题,令写者优先
Thesecondreaders-writersproblem
Abovesolutionissuboptimal,becauseitispossiblethatareaderR1mighthavethelock,awriterWbewaitingforthelock,andthenareaderR2requestsaccess.ItwouldbefoolishforR2tojumpinimmediately,aheadofW;ifthathappenedoftenenough,Wwould
startassoonaspossible.Thisisthemotivationforthesecondreaders-writersproblem,inwhichtheconstraintisaddedthatnowriter,onceaddedtothequeue,shallbekeptwaitinglongerthanabsolutelynecessary.Here,P()isforwaitand
V()isforsignal.Thisisalsocalledwriters-preference.
Asolutiontothewriters-preferencescenarioispresentedbelow:.
code,thesemaphoremutex_1protectsthereadcountvariable,mutex_2protectsthewritecountvariable,themutex'r'protectsthereadingoperation,andthemutex'w'protectsthewritingoperation.
intreadcount,writecount;(initialvalue=0)
semaphoremutex_1,mutex_2,mutex_3,w,r;(initialvalue=1)
READER
P(mutex_3);
P(r);
P(mutex_1);
readcount:=readcount+1;
ifreadcount=1thenP(w);
V(mutex_1);
V(r);
V(mutex_3);
readingisperformed
P(mutex_1);
readcount:=readcount-1;
ifreadcount=0thenV(w);
V(mutex_1);
WRITER
P(mutex_2);
writecount:=writecount+1;
ifwritecount=1thenP(r);
V(mutex_2);
P(w);
writingisperformed
V(w);
P(mutex_2);
writecount:=writecount-1;
ifwritecount=0thenV(r);
V(mutex_2);
调度算法选择
我们如果为每一个作业只建立一个进程,则为了照顾短作业用户,应采用
B;;为照顾紧急作业用户,应采用E,为能实现人机交互作用应采用
C,而能使短作业,长作业及交互作业用户都比较满意时,应采用D
A:FCFS调度算法;B:短作业优先调度算法;C:时间片轮转法;D:多级反馈队列调度算法;E:基于优先权的剥夺调度算法;F:响应比优先算法。
临界区:
多个进程之间共享资源,这样的每个进程的代码段就成为临界区(一段代码)
理发师问题
TheSleeping-BarberProblem.Abarbershopconsistsofawaitingroomwithnchairsandabarberroomwithonebarberchair.Iftherearenocustomerstobeserved,thebarbergoestosleep.Ifacustomerentersthebarbershopandall
chairsareoccupied,thenthecustomerleavestheshop.Ifthebarberisbusybutchairsareavailable,thenthecustomersitsinoneofthefreechairs.Ifthebarberisasleep,thecustomerwakesupthebarber.Writeaprogramtocoordinatethebarberandthecustomers.
Answer:
(1)BarberShop.java
//ThisclassdefinestheBarberShopScenario.
//ThisscenarioallowsNcustomerstoenterit.
//Italsocontainsanumberofchairsthatallowthecustomerstowaitin.
publicclassBarberShop
{
privateintchairNum;
privateintbarber;
privateintchairState[];
staticfinalintFULL=-1;
staticfinalintEMPTY=0;
staticfinalintOCUPIED=1;
staticfinalintSLEEPING=2;
staticfinalintDONE=3;
staticfinalintWAITED=4;
/*============================================================
ConstructanewBarberShopscenarioforcustomerstogethaircutsat.SetthebarbershoptohaveNnumberofchairstowaitin.Thenmakeallthechairstobeinitiallyempty.Alsosetthebarbertobeasleepsothatwhenhisfirstcustomercomesinhecan
wakehimup.
@parampChairNumThenumberofwaitingchairsinthisbarbershop
==================================================================*/
publicBarberShop(intpChairNum)
{
chairNum=pChairNum;
chairState=newint[chairNum];
barber=SLEEPING;
//initializeeverychairinthewaitingroomtobeempty
for(inti=0;i<chairNum;i++)
chairState[i]=EMPTY;
}
/*============================================================
ThismethodiscalledwhenacustomerseesthattheBarberisbusy.Thismeansthatthecustomermustwaitforthebarber.Therefore,findachairinthewaitingroom.WhenthecustomerfindsachairtheysetitsstatetoOCUPIED(sothere'sonlyonecustomer
perchair)andreturntrue.Otherwise,therearenochairsavailablesoreturnfalse.
@parampCustomerThecustomerwantingtofindachairtowaitin.
@returnbooleanTrueifchairisfound;Falseotherwise.
============================================================*/
privatebooleanfindChair(intpCustomer)
{
//trytofindachairtowaitin
inttest=getFirstEmptyChair();
//ifbarbershopisfullreturnfalse
if(test==FULL)
returnfalse;
//otherwisesitdowninthischair
else
chairState[test]=OCUPIED;
returntrue;
}
/*============================================================
ThismethodiscalledbytheCustomerthreadtogetahaircut.IFthebarber'sasleepthenthecustomerwakeshimupandthecustomergetstheirhaircut.IFthebarber'salreadybusythenthecustomertriestofindachairtowaitin.However,ifthereare
nochairsandthebarbersbusy,thentheshopisfull,socustomerwillthenleave.Ifthebarber'sstateisnotsleepingorocupied,thenhecantakethecustomerimmediately.
Thissolutiondoesn'tpreventstarvationforthewaitingcustomers.IfAcustomerfinnalygetsnotifiedtoleavethewaitingstatetheywillbethenexthaircut.Ifanothercustomerenterstheshopatthesametime,thenthatcustomerwillalwayshavetowair
forexistingcustomerstobeserviced.
@paramcustomerThecustomerwantingtogetahaircut
@returnintThestateoftheBarberShopand/orbarber
===========================================================*/
publicsynchronizedintgetHairCut(intcustomer)
{
//ifthebarber'ssleeping,thenwakehimupandtellhimtogettowork
if(barber==SLEEPING)
{
barber=OCUPIED;
returnSLEEPING;
}
//thebarber'sbusytrytowaitforhiminthewaitingroom
elseif(barber==OCUPIED)
{
booleantest=findChair(customer);
//ifbarbershopisfullreturnfullandgetout.
if(test==false)
returnFULL;
else
{
//waitaslongasthebarberisbusy
while(barber==OCUPIED)
{
try{this.wait();}
catch(InterruptedExceptione)
{}
}
//waitingcustomerwillgettobethenexthaircutscheduled.Thereforethey
//standupandgiveuptheirchair.Thisiswhyachairgetsresettoempty.
for(inti=0;i<chairNum;i++)
{
if(chairState[i]==OCUPIED)
{
chairState[i]=EMPTY;
break;
}
}
//setbarbertoocupiedsincethiswaitingcustomerwillgetnexthaircut.
barber=OCUPIED;
returnWAITED;
}
}
//barber'sdone.Thiscustomercangettheirhaircutimmediately
else
{
barber=OCUPIED;
returnDONE;
}
}
/*============================================================
Thismethodiscalledwhenthecustomerhasrecievedtheirhaircutandtheyleavetheshop.Theyfirstchecktoseeifanyoneelseiswaitingintheshop.Ifthereisn'tanyone,thentheywerethelastcustomer.Thismeansthebarbermustgobacktosleep.
Otherwisepoeplearewaiting,sojustsetbarber'sstatetodone.Thennotifyanyonewaiting.
@paramcustomerThecustomerfinishedwithhaircutandleavingshop
@returnvoid
============================================================*/
publicsynchronizedvoidleaveBarberShop(intcustomer)
{
booleantest=isAnyoneWaiting();
if(test==true)
barber=DONE;
else
barber=SLEEPING;
//notifyonlyonewaitingcustomer(ifanyexist)
//thishelpsonperformanceoftheprogram.
notify();
}
/*============================================================
Findthefirstemptychairinthewaitingroomandreturnit.Ifnochairsarefoundthenallchairsareocupiedbyawaitingcustomer.
@returnintThenumberoftheemptychair;FULLotherwise
============================================================*/
privateintgetFirstEmptyChair()
{
//ifanemptychairisfoundreturnit
for(inti=0;i<chairNum;i++)
{
if(chairState[i]==EMPTY)
returni;
}
//allchairsareoccupiedsoreturnFULL
returnFULL;
}
/*============================================================
Testtoseeifthewaitingroomhasanycustomersinit.
@returnbooleanTrueiftherearecustomerswaiting;Falseifempty
============================================================*/
privatebooleanisAnyoneWaiting()
{
//seeifanyoneisinachairwaiting
for(inti=0;i<chairNum;i++)
{
if(chairState[i]==OCUPIED)
returntrue;
}
//couldn'tfindanyonewaiting
returnfalse;
}
}
(2)Customer.java
//Thisclasscreatesacustomerwhoiswantingahaircut.
//Oncethehaircutisreceivedthecustomerthenhasfinishedtheirtask
//andtheyhavetobere-instantiatediftheywantanotherhaircut.
importjava.util.*;
publicclassCustomerimplementsRunnable
{
privateBarberShopshop;
privateintcustomer;
privateintHAIRCUT_TIME=5;
//Constructanewcustomerwiththeiruniqueidentity
//andgivethemabarbershoptoenterfortheirhaircut.
//@parampCustomerThiscustomer'sidentifier.
//@parampShopThebarbershoptheywillgetahaircutin.
publicCustomer(intpCustomer,BarberShoppShop)
{
shop=pShop;
customer=pCustomer;
}
/**
*Therunmethodforthecustomerthreadtriestogetthecustomera
*haircut.
*/
publicvoidrun()
{
intsleeptime=(int)(HAIRCUT_TIME*Math.random());
System.out.println("ENTERINGSHOP:Customer["+customer+"]enteringbarbershopforhaircut.");
inttest=BarberShop.OCUPIED;
//testforthiscustomer'shaircutposibility
test=shop.getHairCut(customer);
//ifthebarberwasbusy,thenthiscustomerhaswaitedinthewaitingroom.
//Thiswaitingcustomerwillnowgetthenexthaircut.Enteringthreadswill
//havetowaitfortheexistingcustomerstobeserviced.Asfaraswhich
//waitingthreadwillgetservicednextisuptotheJVM.
if(test==BarberShop.WAITED)
System.out.println("Barber'sbusy:Customer["+customer+"]haswaitedandnowwantshaircut.");
//otherwise,nooneinbarbershop,wakeupbarberandgethaircut
elseif(test==BarberShop.SLEEPING)
System.out.println("Barber'sasleep:Customer["+customer+"]iswakinghimupandgettinghaircut.");
//thisbarbershopisfull.Thereforeleaveandneverreturn.
elseif(test==BarberShop.FULL)
{
System.out.println("BarberShopfull:Customer["+customer+"]isleavingshop.");
return;
}
//Barber'sreadytotakethiscustomerrightawayforahaircut.
else
System.out.println("HAIRCUT:Customer["+customer+"]isgettinghaircut.");
//customerisnowgettingtheirhaircutforanamountoftime
SleepUtilities.nap();
//haircutfinished.Leavetheshopandnotifyanyonewaiting.
System.out.println("LEAVINGSHOP:Customer["+customer+"]haircutfinished:leavingshop.");
shop.leaveBarberShop(customer);
}
}
(3)SleepUtilities.java
//Utilitiesforcausingathreadtosleep.
//Note,weshouldbehandlinginterruptedexceptions
//butchoosenottodosoforcodeclarity.
publicclassSleepUtilities
{
//NapbetweenzeroandNAP_TIMEseconds.
publicstaticvoidnap(){
nap(NAP_TIME);
}
//Napbetweenzeroanddurationseconds.
publicstaticvoidnap(intduration){
intsleeptime=(int)(NAP_TIME*Math.random());
try{Thread.sleep(sleeptime*1000);}
catch(InterruptedExceptione){}
}
privatestaticfinalintNAP_TIME=5;
}
(4)CreateBarberShopTest.java
//TestStubfortheBarberShop\Customerproblem.
//Thisclassaddscustomerstoaconstructedbarbershopindefinately.
publicclassCreateBarberShopTestimplementsRunnable
{
staticfinalprivateintWAIT_TIME=3;
staticpublicvoidmain(String[]args)
{
newThread(newCreateBarberShopTest()).start();
}
publicvoidrun()
{
//createthebarbershop
BarberShopnewShop=newBarberShop(15);
intcustomerID=1;
//addthespecifidnumberofthreadstoshop
while(customerID<=10000)
{
//addcustomerstothebarbershop
newThread(newCustomer(customerID,newShop)).start();
customerID++;
//waitthisamountoftimebeforeaddinganothercustomertoshop
SleepUtilities.nap();
}
}
}
相关文章推荐
- 面试复习重点——基础篇:操作系统、计算机网络、设计模式【山科大牛陈磊整理】
- 面试复习重点——基础篇:操作系统、计算机网络、设计模式【山科大牛陈磊整理】
- 操作系统期末复习之 常用调度算法整理
- 操作系统复习知识点整理
- 操作系统复习整理
- 南京晓庄学院 操作系统 复习提纲(整理)
- 复习整理8:Docker:一个装应用的容器
- windows7操作系统崩溃后的修复技巧(整理)
- [综合面试] 牛人整理分享的面试知识:操作系统、计算机网络、设计模式、Linux编程,数据结构总结
- 操作系统常见面试的一些基础知识整理
- JSP指令元素(page指令/include指令/taglib指令)复习整理
- 考试复习整理
- [综合面试] 牛人整理分享的面试知识:操作系统、计算机网络、设计模式、Linux编程,数据结构总结
- 操作系统知识点整理(持续更新)
- 180226—【操作系统】复习:中断机制
- 操作系统复习---框架图
- 常见的操作系统使用的文件系统整理
- css复习整理(四):css定位
- 软考嵌入式系统工程师知识点整理(嵌入式操作系统)
- Linux操作系统不需要碎片整理的原因是什么?