操作系统复习整理



操作系统概念,在计算机系统中的作用:

操作系统是计算机系统中的一个系统软件。一方面控制和管理计算机中的硬件和软件资源,合理的组织计算机工作流程,以使这些资源得到有效的利用。另一方面为用户提供一个功能强、使用方便的工作环境,从而在用户和计算机之间起到接口的作用。

可扩充硬件功能,为用户提供良好的运行环境

现代操作系统的基本特征程序的并发执行资源共享、 操作的异步性

操作系统例题:

操作系统有多种类型:允许多个用户以交互方式使用计算机的操作系统,称为 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)交互作用性:用户能和电脑进行人机对话。

适用于计算量小的不成熟的作业。

 

系统调用System Call

指运行在用户态的程序向错做系统内核请求更高权限运行的服务,比如硬件相关的服务,创建并执行新进程。系统调用提供了用户程序与操作系统之间的接口。

特权指令:

常见的特权指令有以下几种:

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)系统开销:在创建或撤销进程时,由于系统都要为之分配和回收资源,导致系统的开销明显大于创建或撤销线程时的开销。但是进程有独立的地址空间,一个进程崩溃后,在保护模式下不会对其它进程产生影响,而线程只是一个进程中的不同执行路径。线程有自己的堆栈和局部变量,但线程之间没有独立的地址空间,一个线程死掉等于整个进程死掉,所以多进程的程序要比多线程的程序健壮,但在进程切换时,耗费资源较大,效率要差一些。

 

从进程演化出线程,最主要的目的就是更好的支持SMPSymmetricMulti-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.What is the deadlock?

Answer:A set of blocked processes each holding aresource and waiting to acquire a resource held by another process in the set.

How to prevent the deadlock occurred ?

Answer:By ensuring that at least oneof four conditions(Mutual Exclusion, Hold and Wait ,No Preemption , CircularWait) cannot hold, we can prevent the occurrence of a deadlock.

How to avoid the deadlock occurred ?

To use Safety Algorithm:

If a system is in safe state Þ no deadlocks.

If a system is in unsafe state Þ possibility of deadlock.

Avoidance Þ ensure that a system will neverenter an unsafe state.

读者-写者问题,令写者优先

https://en.wikipedia.org/wiki/Readers%E2%80%93writers_problem

The secondreaders-writers problem

Above solution is suboptimal,because it is possible that a reader R1 might have the lock, a writer W be waiting for the lock, and then areader R2 requests access. It would be foolishfor R2 to jump in immediately, ahead of W; if that happened oftenenough, W would starve.Instead, W should start as soon as possible. Thisis the motivation for the secondreaders-writers problem, in which the constraint is added that no writer, once added to the queue,shall be kept waiting longer than absolutely necessary. Here, P() is for waitand V() is for signal. This is also called writers-preference.

A solution to the writers-preference scenario is presented below:.[1] Inthis code, the semaphore mutex_1 protects the readcount variable, mutex_2protects the writecount variable, the mutex 'r' protects the reading operation,and the mutex 'w' protects the writing operation.

int readcount, writecount; (initial value = 0)
semaphore mutex_1, mutex_2, mutex_3, w, r ; (initial value = 1)
 
READER
  P(mutex_3);
    P(r);
      P(mutex_1);
        readcount := readcount + 1;
        if readcount = 1 then P(w);
      V(mutex_1);
    V(r);
  V(mutex_3);
 
 
  reading is performed
 
  P(mutex_1);
    readcount := readcount - 1;
    if readcount = 0 then V(w);
  V(mutex_1);
 
WRITER
  P(mutex_2);
    writecount := writecount + 1;
    if writecount = 1 then P(r);
  V(mutex_2);
 
  P(w);
    writing is performed
  V(w);
 
  P(mutex_2);
    writecount := writecount - 1;
    if writecount = 0 then V(r);
  V(mutex_2);

调度算法选择

我们如果为每一个作业只建立一个进程,则为了照顾短作业用户,应采用  B  ;;为照顾紧急作业用户,应采用   E  ,为能实现人机交互作用应采用 C    ,而能使短作业,长作业及交互作业用户都比较满意时,应采用 D  

 A: FCFS调度算法;B:短作业优先调度算法;C:时间片轮转法;D:多级反馈队列调度算法;E:基于优先权的剥夺调度算法;F:响应比优先算法。

临界区:

多个进程之间共享资源,这样的每个进程的代码段就成为临界区(一段代码)

 

理发师问题

The Sleeping-Barber Problem. Abarbershop consists of a waiting room with n chairs and a barber room with onebarber chair. If there are no customers to be served, the barber goes to sleep.If a customer enters the barbershop and all chairs are occupied, then thecustomer leaves the shop. If the barber is busy but chairs are available, thenthe customer sits in one of the free chairs. If the barber is asleep, thecustomer wakes up the barber. Write a program to coordinate the barber and thecustomers.

Answer:

(1) BarberShop.java

//This class defines the Barber ShopScenario.

//This scenario allows N customers toenter it.

//It also contains a number of chairsthat allow the customers to wait in.

public class BarberShop

{

   private int chairNum;

   private int barber;

   private int chairState[];

   static final int FULL = -1;

   static final int EMPTY = 0;

   static final int OCUPIED = 1;

   static final int SLEEPING = 2;

   static final int DONE = 3;

   static final int WAITED = 4;

   

/*============================================================

Construct a new Barber Shop scenario forcustomers to get haircuts at. Set the barber shop to have N number of chairs towait in.  Then make all the chairs to beinitially empty.  Also set the barber tobe asleep so that when his first customer comes in he can wake him up.

@param pChairNum The number of waitingchairs in this barber shop

==================================================================*/

   public BarberShop(int pChairNum)

   {

       chairNum = pChairNum;

       chairState = new int[chairNum];

       barber = SLEEPING;

       

       //initialize every chair in the waiting room to be empty

       for(int i = 0; i < chairNum; i++)

            chairState[i] = EMPTY;

   }

   

/*============================================================

This method is called when a customersees that the Barber is busy. This means that the customer must wait for thebarber.  Therefore, find a chair in thewaiting room.  When the customer finds achair they set its state to OCUPIED (so there's only one customer per chair)and return true. Otherwise, there are no chairs available so return false.

@param pCustomer The customer wanting tofind a chair to wait in.

@return boolean True if chair is found;False otherwise.

============================================================*/

   private boolean findChair(int pCustomer)

   {

       //try to find a chair to wait in

       int test = getFirstEmptyChair();

       

       //if barber shop is full return false

       if(test == FULL)

            return false;

       //otherwise sit down in this chair

       else

            chairState[test] = OCUPIED;

       

       return true;

   }

   

/* ============================================================

This method is called by the Customerthread to get a haircut.  IF the barber'sasleep then the customer wakes him up and the customer gets their haircut.  IF the barber's already busy then thecustomer tries to find a chair to wait in. However, if there are no chairs and the barbers busy, then the shop isfull, so customer will then leave.  Ifthe barber's state is not sleeping or ocupied, then he can take the customer immediately.

This solution doesn't prevent starvationfor the waiting customers.  If A customerfinnaly gets notified to leave the waiting state they will be the nexthaircut.  If another customer enters theshop at the same time, then that customer will always have to wair for existingcustomers to  be serviced.

@param customer The customer wantingto get a haircut

@return int The state of the Barber Shopand/or barber

===========================================================*/

   public synchronized int getHairCut(int customer)

   {

       //if the barber's sleeping, then wake him up and tell him to get to work

       if(barber == SLEEPING)

       {

            barber = OCUPIED;

            return SLEEPING;

       }

       //the barber's busy try to wait for him in the waiting room

       else if(barber == OCUPIED)

       {

            boolean test = findChair(customer);

           

            //if barber shop is full returnfull and get out.

            if(test == false)

                return FULL;

            else

            {

               //wait as long as thebarber is busy

                while(barber == OCUPIED)

                {

                    try{ this.wait(); }

                    catch(InterruptedExceptione)

                    {}

                } 

                

//waiting customer will get to be thenext haircut scheduled.  Therefore they

//stand up and give up their chair.  This is why a chair gets reset to empty.

                for(int i = 0; i < chairNum;i++)

                {

                    if(chairState[i] ==OCUPIED)

                    {

                        chairState[i] = EMPTY;

                        break;

                    }

                }

               

//set barber to ocupied since thiswaiting customer will get next haircut.

               barber = OCUPIED;

                return WAITED;

            }          

       }

//barber's done.  This customer can get their haircutimmediately

       else

       {

            barber = OCUPIED;

            return DONE;

       }

   }

   

/*============================================================

This method is called when the customerhas recieved their haircut and they leave the shop.  They first check to see if anyone else iswaiting in the shop.  If there isn'tanyone, then they were the last customer.This means the barber must go back tosleep.  Otherwise poeple are waiting, sojust set barber's state to done.  Thennotify anyone waiting.

@param customer The customer finishedwith haircut and leaving shop

@return void

============================================================*/

   public synchronized void leaveBarberShop(int customer)

   {

       boolean test = isAnyoneWaiting();       

       if(test == true)

            barber = DONE;

       else

            barber = SLEEPING;

       //notify only one waiting customer (if any exist)

       //this helps on performance of the program.

       notify();

   }

       

/*============================================================

Find the first empty chair in the waitingroom and return it.  If no chairs arefound then all chairs are ocupied by a waiting customer.

@return int The number of the emptychair; FULL otherwise

============================================================*/

   private int getFirstEmptyChair()

   {

       //if an empty chair is found return it

       for(int i = 0; i < chairNum; i++)

       {

            if(chairState[i] == EMPTY)

                return i;

       }

       //all chairs are occupied so return FULL

       return FULL;

   }

   

/*============================================================

Test to see if the waiting room has anycustomers in it.

@return boolean True if there arecustomers waiting; False if empty

============================================================*/

   private boolean isAnyoneWaiting()

   {

       //see if anyone is in a chair waiting

       for(int i = 0; i < chairNum; i++)

       {

            if(chairState[i] == OCUPIED)

                return true;

       }

       //couldn't find anyone waiting

       return false;

   }

}

(2) Customer.java

//This class creates a customer who iswanting a haircut.

//Once the haircut is received thecustomer then has finished their task

//and they have to be re-instantiated ifthey want another haircut.

import java.util.*;

public class Customer implements Runnable

{

   private BarberShop shop;

   private int customer;

   private int HAIRCUT_TIME = 5;

   

// Construct a new customer with theirunique identity

//and give them a barber shop to enterfor their haircut.

    //@parampCustomer This customer's identifier.

//@parampShop The barber shop they will get a haircut in.

   public Customer(int pCustomer, BarberShop pShop)

   {

       shop = pShop;

       customer = pCustomer;

   }

   

   /**

    * The run method for the customer thread tries to get the customer a

    * haircut. 

   */

   public void run()

   {

       int sleeptime = (int) (HAIRCUT_TIME * Math.random() );

       System.out.println("ENTERING SHOP: Customer [" + customer +"] entering barber shop for haircut.");

       int  test = BarberShop.OCUPIED;

       //test for this customer's haircut posibility

       test = shop.getHairCut(customer);

       //if the barber was busy, then this customer has waited in the waitingroom.

       //This waiting customer will now get the next haircut.  Entering threads will

       //have to wait for the existing customers to be serviced.  As far as which

       //waiting thread will get serviced next is up to the JVM.

       if(test == BarberShop.WAITED)

            System.out.println("Barber'sbusy: Customer [" + customer + "] has waited and now wantshaircut.");

       //otherwise, no one in barber shop, wake up barber and get haircut

       else if (test == BarberShop.SLEEPING)

            System.out.println("Barber'sasleep: Customer [" + customer + "] is waking him up and gettinghaircut.");

       //this barber shop is full. Therefore leave and never return.

       else if (test == BarberShop.FULL)

       {

           System.out.println("BarberShop full: Customer [" + customer + "] is leaving shop.");

            return;

       }

       //Barber's ready to take this customer right away for a haircut.

       else

            System.out.println("HAIRCUT:Customer [" + customer + "] is getting haircut.");              

       //customer is now getting their haircut for an amount of time

       SleepUtilities.nap();

       //haircut finished.  Leave theshop and notify anyone waiting.

       System.out.println("LEAVING SHOP: Customer [" + customer +"] haircut finished: leaving shop.");

       shop.leaveBarberShop(customer);

   }

}

(3) SleepUtilities.java

//Utilities for causing a thread tosleep.

//Note, we should be handling interruptedexceptions

//but choose not to do so for codeclarity.

public class SleepUtilities

{

    //Nap between zero and NAP_TIME seconds.

    publicstatic void nap() {

        nap(NAP_TIME);

    }

    //Napbetween zero and duration seconds.

    publicstatic void nap(int duration) {

           int sleeptime = (int) (NAP_TIME* Math.random() );

           try {Thread.sleep(sleeptime*1000); }

           catch (InterruptedException e){}

    }

    privatestatic final int NAP_TIME = 5;

}

(4) CreateBarberShopTest.java

//Test Stub for the BarberShopCustomerproblem.

//This class adds customers to aconstructed barber shop indefinately.

public class CreateBarberShopTestimplements Runnable

{

   static final private int WAIT_TIME = 3;

   static public void main(String [] args)

   {

       new Thread(new CreateBarberShopTest()).start();

   }

   

   public void run()

   {

       //create the barber shop

       BarberShop newShop = new BarberShop(15);

       int customerID = 1;

       

       //add the specifid number of threads to shop

       while(customerID <= 10000)

       {

            //add customers to the barber shop

            new Thread(new Customer(customerID,newShop)).start();

            customerID++;

            //wait this amount of time beforeadding another customer to shop

            SleepUtilities.nap();

       }     

   }

}

原文地址:https://www.cnblogs.com/f8master/p/3826077.html