操作系统学习笔记(一)

操作系统

chapter1~9,11,12

chapter 1 计算机系统概述

1.1 计算机基本构成

一个或多个CPU(处理器),main memory(内存),输入输出模块,系统总线

processer Register

register:memoey inside CPU

作用:减少CPU和主存之间的传递的时间(enable CPU to minimize main-memory references)

User-visiable register:用户可见寄存器:调试代码的阶段可以调用通用寄存器的数据[做加法操作时,存放加数,被加数]

Control and status register:控制和状态寄存器:比如控制代码起始位置

PC:program counter:下一条指令所在的内存单元位置

IR:instruction register:最近被调用的指令

PSW:program status word:程序状态设置,可以中断

存储器地址寄存器(MAR)

存储器缓冲寄存器(MBR)

输入输出缓冲寄存器

1.2 指令执行

程序运行周期

  1. 开启进程(第一条指令的位置被放入PC),程序被加载到进程所对应的内存空间的位置,代码段(int,赋值等操作)和数据段(a,b,c的值)被分离
  2. 根据PC中的地址,找到内存中的下一条指令,并放入IR
  3. PC的值加一,指向下一条指令的地址[遇到if操作则会有jump更改PC中的值]
42B7A6A3F3FD48D5A698F54284286D54 432AED9CC47A4D59C43AE1568BC88FD3

操作码和地址分别对应了IR当中存储的指令的第一位和后三位

  1. step2 中的IR中的1940,1为操作码,转为0001:从内存中载入AC(数据寄存器:寄存数据),940为内存中地址
  2. step5中的IR的2941,2为操作码,转为0010,将AC载入内存941的位置,将0005存入内存的941位置

指令周期

CE3CACD25BC3F714E12ABE8EAEF1E2A2
  1. processor fetches instructions from memory(从主存中取指令)
  2. processor execute each instruction
1.3 中断
  1. I/O设备的速度低于CPU的速度,中断能够提高CPU利用率
  2. 用于计数
  3. 避免CPU被独占

中断是一种机制,打断正常CPU执行过程,然后提供需要的服务

中断和指令周期
08D031AADEF9DE72868672E238692E93

中断必须在指令执行完毕之后才能检查到,在指令执行的过程中不允许中断

D4CE2F6E5837D58A0F3CF1CDB281EBF6
中断的处理方式
B86C0680364CC9F5010916D9304CB864
  1. 外设硬件产生一个中断

  2. 处理器执行完毕当前的指令,然后检查中断

  3. 将PSW和PC寄存器当中的数据和指针,推入栈(特殊的内存的区域,用户无法调用)

  4. 处理器将中断编号加载到PC寄存器当中

  5. 中断服务程序将PC和PSW原先的数据进行保存

  6. 执行中断程序,执行完毕之后恢复PC和PSW

E80A79B5E2331963ADBC335F591CF112
多个中断的处理

method 1

直接拒绝下一个中断,中断顺序执行

method 2

中断程序按照优先级顺序执行(给予中断优先级,高优先级可以中断低优先级)

99F5F38BCCED49DAF82B98A99DE18090

multiprogramming(多道程序)

the time to complete I/O opearation is much greater than user code between I/O calls(如果只处理单一I/O操作处理器就会被浪费,处理器需要等待I/O操作)

solution: allow multiple user program to be active(多个I/O操作同时进行)

1.4 存储结构
F8515E61DA7CEA6875FF07CB99EA43B3
局部性原理

频繁的访问相邻的指令或者数据

B28949504EE1258EAA2F2D7E2396CF48

将一部分局部的代码或者数据存入缓存cache当中,这一部分局部往往会被重复使用,如果没有被重复使用则称为未命中,再从主存调用

1.5 cache memory
method 1

可编程 I/O:I/O设备直接更改寄存器的状态

method 2

中断驱动 I/O:发出中断信号给予CPU

method 3

DMA直接内存访问:在CPU之外多出了DMA控制器,CPU将拷贝数据的工作交给DMA,让DMA直接从内存读取

例:

When a new block of data is written into cache memory, the following determines which cache location the block will occupy

replacement algorithm(替换算法)

write policy:何时从缓存写入内存

mapping function:映射策略

1.6 I/O communication techniques
  1. programmed I/O

    I/O module performs the action, not the processor

    I/O module sets appropriate bits in the I/O status register

    Processor checks status until operation is complete

    image-20200913094529582

    Disadvantage: It is a time-consuming process that keeps the processor busy needlessly

  2. Interrupt-Driven I/O

    Processor is interrupted when I/O module ready to exchange data

    Processor saves context of program executing and begins executing interrupt-handler

    image-20200913094716371

    Advantage:No needless waiting, so more efficient than programmed I/O

    Disadvantage :Still consumes a lot of processor time because every word read or written passes through the processor

  3. Direct Memory access

    Transfers a block of data directly to or from memory,I/O exchanges occur directly with memory

    Processor continues with other work

    An interrupt is sent when the transfer is complete

    Advantage:Relieves the processor responsibility for the exchange

chapter 2 操作系统概述

2.1 操作系统目标与功能

操作系统是控制应用程序执行的程序,是应用程序和计算机硬件之间的接口

目标:方便,有效,扩展能力

what is an operaing system

  1. acts as an interface netween applications and hardware

  2. a program that controls the execution of application program

  3. the Operating System as Resource Manager

    –Operating system frequently relinquishes(放弃) and regains control of the processor

User->appplication->operating system->hardware

2.1.1 作为接口的操作系统
1E00497C93140A97219E1AB991AD9074

计算机系统三种重要接口

  1. 指令系统体系结构(ISA):定义了计算机遵循的机器语言指令系统(硬件和软件的分界线)

  2. 应用程序二进制接口(ABI):定义了程序之间二进制可移植性的标准(操作系统的系统调用接口,以及系统所使用的硬件资源)

    ABI和API之间的library(库函数)[可以被应用程序调用:printf],会进行system call调用CPU内核,CPU内核对硬件进行操作

  3. 应用程序编程接口(API):允许应用程序访问系统的硬件资源和服务

作为资源管理器的操作系统
BEA0AEC5820E16B03DB005F5C4BF2E59

操作系统控制机制

  1. 操作系统和普通计算机软件相同,是由处理器执行的一段程序
  2. 操作系统会释放对处理器的控制,依赖处理器恢复控制
image-20200916082629474

Shell:操作系统对用户提供的接口

CLI :command line interface

GUI:graphical user interface

Kernel:Portion of operating system that is in main memory

​ Contains most frequently used functions(库函数)

操作系统的发展史

串行处理
  1. 用户必须顺序访问计算机:调度问题,准备时间

  2. The programmer interacted directly with the computer hardware

调度:使用硬拷贝登记表预定机器时间

准备时间:单个程序(作业),会向内存中加载编译器和高级语言程序[这段程序执行之前的时间称为准备时间]

简单批处理系统(Simple Batch Systems)

中心思想:监控程序

image-20200916083908270

操作员将大批量作业按顺序组织成批(batch),将整个批作业放在输入设备中

process:每个程序完成之后回到监控程序,监控程序自动加载下一个程序

C8299F65321F32844F8E03DCBAE76E92

常驻监控程序:监控程序控制事件的顺序,储在内存当中

处理器角度:读入一个作业之后,处理器遇到监控程序中的分支指令,读入下一个作业并存储到内存中

Job Control Language(JCL):编写监控程序的语言

监控程序其他功能

  1. 内存保护(memory protection):用户程序运行的过程中不能改变包含监控程序的内存区域

    用户模式:特权指令不能执行,部分内存受保护

    内核(系统)模式:不仅可以执行特权指令,可以访问受保护内存区域

  2. 定时器(Timer):定时器用于防止一个作业独占系统

  3. 专权指令(privileged instruction):部分机器指令被设计成特权指令,只能由监控程序执行

  4. 中断(interrupts):监控程序能够使操作系统让用户程序放弃控制权

多道批处理系统(Multiprogrammed Batch Systems,增大处理器使用)

简单批处理的问题:I/O设备相对于处理器而言速度过慢,处理器需要等待I/O

7CCFDA3B29FAD81BEAAB9A1D741D7CC9

多道批处理:当一个作业需要等待I/O时,处理器可以切换到另一个不在等待I/O的作业进行执行

和分时系统的区别在于:批处理系统A是因等待I/O设备被迫让出CPU资源,而分时则是操作系统强制使JOB让出资源

需要的硬件功能:支持I/O中断和直接存储器访问

例:假设有一台多道程序的计算机,每个作业都有相同的特征,即在一个计算周期T里,I/O占用第一和第四个1/4周期,处理器占有第二和第三个1/4周期。而各个作业占用的I/O设备各不相同。如果计算机被任何一个作业单独占用的话,完成作业总共需要1个计算周期。假设使用时间片轮转进程调度策略,而且I/O操作能与处理器操作重叠,不同的I/O设备可以同时运行。定义以下变量:
周转时间=完成一个作业的实际时间
吞吐量=每周期T完成的作业的数量的平均值
处理器使用率=处理器处于活动状态(非等待)的时间在总时间中占的百分比

若有两个作业同时要求运行,作业l的优先级较高,作业都只运行一次。进程状态转换时的操作系统开销忽略不计,且时间片的大小远小于T。
计算:
(1) 作业1和作业2各自的周转时间。
(2) 从作业开始运行,到两个作业都已完成的瞬间,计算机系统的吞吐量和处理器使用率。

708B4436472AB9E7B76A7AD23AF80DE1

T1 = T, T2=3/2T

分时系统

分时技术:多道程序允许处理器同时处理多个交互作业(减小反应时间)

Processor‘s time is shared(时间片技术) among multiple users’ jobs

操作系统强制让JOB1让出资源,给予任务2,不允许JOB1独占CPU资源过长时间(操作系统会每隔一段时间产生一个中断)

产品:CTSS

多个用户可以通过终端同时访问系统,由操作系统控制每个用户程序在很短的时间交替执行

75A2BBD9BB7536D0BF974EBD28EEFD1D

分时系统实例(每个一段时间产生一个中断,监控程序获得控制权)

952BEDE05F46FFB3E21C21F5AC23BA4A
  1. 监控程序载入JOB1,并将控制权转交给它
  2. 监控程序决定将控制权转交给JOB2,JOB2>JOB1,所以JOB1被写出,JOB2被写入
  3. JOB3被载入,部分JOB2仍然储存在存储器当中
  4. 监控程序将控制权转会JOB1,JOB2部分将被写出
  5. 载入JOB4时,JOB1和JOB2的一部分仍然存在储存器当中

主要成就

进程(process)

进程映像文件:4K

  1. An executable program/code

  2. Associated data needed by the program

  3. execution context(执行上下文) of the program

    all information the operating system needs to manage the process

The process is realized as a data structure

All inforamtion the operating system needs to manage the process is stored in the data structure

BA280EED09EEF7789CC8D95EBD59BA6F

process list:进程相关信息,方便操作系统进行管理

存储管理

操作系统负责的存储管理:

  1. process isolation(进程隔离)

    不允许进程访问其他进程的数据

  2. automatic allocation and management(自动分配和管理)

    多个进程需要执行,操作系统管理进程何时进入内存,进入内存的地址

  3. support of modular programming(模块化程序设计)

  4. Long-term storage(长期存储)

  5. Protection and access control (保护与存取控制)

虚拟内存

进程只有一部分存在在内存当中,操作系统在接收到进程页缺失后会通过内存管理单元将硬盘中的剩余内容加载到内存

No hiatAllows programmers to address memory from a logical point of view

虚拟内存方式允许程序以逻辑的方式访问存储器

Page:Allows process to be comprised of a number of fixed-size blocks, called pages

进程内容从硬盘加载进入内存的单位是以页的方式

Virtual Memory Addressing(内存管理单元)
image-20200916094555160

作用:映射程序中使用的虚拟内存地址和内存中的真实物理内存地址,以及硬盘存储的地址

安全和数据保护
  1. Availability 不被中断

  2. Confidentiality保密性,授权

  3. Data integrity 不被未授权篡改

  4. Authenticity认证

调度和资源管理
  1. Manage the resources (such as CPU, Main Memory, I/O devices)

  2. Schedule/调度 these resources to various active processes/进程

fairness(公平性)

Differential responsiveness(有差别响应)

Efficiency(高效性)

现代操作系统
Microkernel architecture(微内核)

对比OS的单内核完成所有管理工作,它含基本功能

Multithreading(多线程)

进程含多线程,资源占用少,调度单位

线程:进程内部允许小任务并发执行:

dispatchable unit of work

execute sequentially and is interruptable

Symmetric multiprocessing (SMP)对称多处理

具有多核CPU,且完全对等,允许多CPU并发进行,防止单核处理器失效

availability: 对抗单核处理器失效

incremental growth:增量增长,增加处理器

scaling:配置灵活

114B8CAF94D233696169DE6BB52A9397
Load of OS

加电->读BIOS(基本输入输出程序,存储在ROM当中)->读加载程序->读OS内核映像文件

image-20200916103730770

chapter 3 process description and control

3.1 what is a process

  1. a program in execution

  2. an instance of a program running on a computer

  3. the entity(实体) that can be assigned to and executed on a processor

  4. a unit of activity characterized by:

    the execution of a sequence of instructions

    a current state

    an associated set of syustem resource

process control block(进程控制模块)

  1. contains the process elements
  2. created and managed by the operating system
  3. allow support for multiple process

process element

identifier(进程编号)

state(状态)

priority(进程优先权限)

program counter(PC):储存下一条指令地址

memory pointer(地址指针:数据临时存放的栈在内存的位置)

context data:上下文数据(已经经过计算的数据,需要保存后期应用)

I/O status information

accounting information:CPU的信息

3.2 process states

process creation

20200921-210946
  1. by user:new app
  2. by OS: like process interrupt
  3. by existing process: codeblocks

process termination

20200921-211124 20200921-211234
  1. errors: data/protection/illeagal behavior
  2. by parent process
  3. noraml completion
3.2.1 trace of process(进程轨迹)
  1. sequence of instruction that execute for a process(进程执行轨迹)
  2. dispatcher(调度器) switches the processor from one process to another
20200921-211717
3.2.2 a two state process model

process states: running,Not-running

image-20200922141445294 image-20200922141528158

Not-running的情况:

  1. ready to execute
  2. waiting for I/O(blocked)

Dispatcher(分派器) can’t select the process that has been in the queue the longest because it may be blocked

disadvantage:进程可能出现在等待I/O设备的状态,并没有进行描述;单队列出现搜索队列时间过长(进程优先级不同,需要检索下一个执行的进程)

3.2.3 A five-state model

Running(运行态)

Ready (就绪态):队列当中正在等待

Blocked(阻塞态):进程处于等待I/O设备

New (新建态):已经分配了进程控制块,进程的数据,指令仍未进行分配的状态

Exit (退出态):进程已经结束

image-20200922141956942 image-20200922142112036

using two queues

image-20200922142143047

events occur:外设准备完毕的中断信号

Multiple Blocked Queues

image-20200922142212585

将外设完成的中断信号进行分类,将阻塞的进程进行分类

disadvantage:consider the memory spaces allocated for all the processes(内存空间不足)

Less impact on capability of the computer system

3.2.4 suspended process(挂起的进程)

Processor is faster than I/O so all processes could be waiting for I/O(处理器远快于外部设备,进程往往再等待I/O设备)

Blocked state becomes suspend state when swapped to disk(挂起的进程会被包装到硬盘当中节省主存空间)

image-20200922142729522 image-20200922142811015

state:blocked/suspended;ready/suspended

3.3 process description

3.3.1 Operating System Control Structures
  1. Information about the current status of each process and resource (每个进程和资源的当前状态)
  2. Tables are constructed for each entity the operating system manages (操作系统构造并维护他所管理的所有实体的信息表)

**MEM(占用内存),I/O(需要的I/O设备),FILE(引用的文件),PROCESS(进程简要信息)**四张信息表格进行描述,四张表交叉引用

image-20200922145812396

Memory table

  1. allocation main memory to process(分配给进程内存)
  2. allocation of secondary memory to process(分配给进程辅存)
  3. protection attributes for access shared memory region(共享内存的保护属性)
  4. information needed to manage virtual(虚拟内存管理信息)

File table

existence of files

location on secondary memory

status

3.3.2 process control structure

process table 包含 进程映像,进程映像包含PCB 和栈空间,PCB中包含进程结构信息

process image(进程映像)

the collection of program data stack and attributes(PCB:process control block)

process table

location of each page of each process image

process image

process attributes(PCB)

process control block(PCB)

  1. Process Identification
  2. Processor State Information
  3. Process Control information

PCB contains: Structuring information: pointers to linked list of queues

image-20200923095223501

3.4 process control

The possible events that may give control to the OS include:

  1. interrupt

    clock interrupt

    I/O interrupt

    memory fault

  2. Trap

    error or exception occurred

    –may cause process to be moved to Exit state

  3. 2.Supervisor call (System Call)

    file open

process switching
  1. Save context of processor including program counter and other registers

  2. Update the process control block of the process and change the process’s state that is currently in the Running state

  3. Move process control block to appropriate queue – ready; blocked; ready/suspend

  4. Select another process for execution

  5. Update the process control block of the process selected and change it state

  6. Update memory-management data structures

  7. Restore context of the selected process

3.5 execution of the operating system(操作系统是否为进程)

Non-process Kernel(无进程内核)

内核存在于进程之外

image-20200926161208342
Execution Within User Processes(在用户进程中执行)

操作系统在用户进程当中分配部分的空间,每个用户进程都有部分的空间分配给操作系统

image-20200926161312168 image-20200926161336596
Process-Based Operating System(基于进程的OS)

操作系统作为独立的进程进行运行,但是不占据用户进程的空间

image-20200926161422768
fork函数
int main(void)
{
int   fpid=fork();     //fork会创建一个新的子进程,返回值为0,在父进程中返回子进程id
int   pid = getpid();  //获取父进程自己的pid
if(fpid)
     printf("father");
else
      printf("child");
}
execv函数
int main()
{
    fpid=fork()  ;
	//fork之后子进程和父进程同时开始执行
char *args[]={"./EXEC",NULL};
   //execv的参数是可执行文件(包括out经过链接的,和.o文件经过编译没有链接库)
   if(fpid==0)
	execv(args[0],args);     
   //原来子进程和父进程代码相同,在执行方法之后,将新的代码拷贝到子进程当中
   printf("Ending-----");
   if(fpid)
       waitpid(pid);       //利用waitpid确定是父进程并等待
   return 0;
}
int main()  {
    int i;
    printf("I am EXEC.c called by execv() ");
return 0;
}
//wait: 直接认定自己为父进程,父进程等待子进程终止并返回
//why:进程只能释放自己的空间,不能销毁自己的PCB,父进程销毁子进程的PCB
//孤儿进程:父进程已经结束,子进程尚未结束

chapter 4 Threads,SMP and microkernels

4.1 process and threads

Resource ownership(资源所有权)

process includes a virtual address space to hold the process image

资源所有权的单位称为进程或者任务

Scheduling/execution(调度/执行)

execution path that may be interleaved with other processes

操作系统调度的单位称为线程或轻量进程

进程占用资源,线程调度使用资源(可执行文件执行就会打开进程,一个进程中可以有多个线程)

4.1.1 Multithreading

单线程指一个进程中只有一个线程在执行的传统方法(线程也就是进程)

Multithreading refers to the ability of an OS to support multiple threads of execution within a single process

操作系统支持在一个进程中执行多个线程并行执行的能力

比如: 播放器播放音乐需要:播放,画面,网络(出现多个线程,分配到操作系统分时进行)

image-20200927091931945

Process

Have a virtual address space(虚拟地址空间) which holds the process image( code, data, stack and PCB)

Protected access to processors, memory, other processes(与其他进程通信), files, and I/O resources

Contains one or more threads

Thread(操作系统调度执行单位)

An execution state (running, ready, etc.)

Saved thread context when not running(pc,保存自己的上下文)

Has an execution stack

Some per-thread static storage for local variables(独立局部变量保存:user stack)

Access to the memory and resources of its process (全局变量保存,减少进程信息通信)

all threads of a process share this

image-20200926163506054

线程的优点

  1. Takes less time to create a new thread than a process (创建快)

  2. Less time to terminate a thread than a process (结束快,由进程关闭)

  3. Less time to switch between two threads within the same process (切换快,不需要操作系统进行关闭,由进程直接关闭)

  4. Since threads within the same process share memory and files, they can communicate with each other without invoking the kernel (通信快)

线程会受到进程动作的影响

  1. 挂起进程会挂起该进程的所有线程(进程是内存空间分配的单位,进程被从内存移动到硬盘,连带着线程一起挂起)——线程没有挂起状态
  2. 终止进程会终止该进程的所有线程——线程全部结束后,进程才能结束
4.1.2 thread functionality

Operations associated with a change in thread state

  1. Spawn(派生):Spawn another thread(创建新的线程)
  2. Block(阻塞)and unblock——一个线程阻塞不会导致整个进程被阻塞
  3. finsh
对多个服务器发送请求

单线程

image-20200927093803083

单线程,只能串行的依此向两个服务器发出请求

多线程

image-20200927093827966

多线程情况下,分出两个线程分别对两个服务器发出请求,两个线程会交替调用操作系统(和父子进程调用操作系统的方式相同)

4.2 types of threads

4.2.1 User-Level Threads (ULT,用户级线程)
  1. All thread management is done by the application(线程的调度会在用户模式(线程库)下完成)

  2. The kernel is not aware of the existence of threads & scheduling is done on a process basis

image-20200926165632672 image-20200927095041463
  1. 进程正在运行,分配的CPU给线程2,线程1处于就绪态

  2. 线程2,访问I/O设备,进程被阻塞

  3. 线程2需要访问线程1的数据,自身被阻塞,给线程1让出数据

  4. 线程2进入阻塞,进程仍旧在执行

4.2.2 Kernel-Level Threads(KLT,内核级线程)
  1. Kernel maintains context information for the process and the threads

  2. Scheduling is done on a thread basis

image-20200926165705090

chapter 5 互斥和同步

sleep结束之后假设两个线程都处于就绪/执行状态会使得CPU重新分配

多线程编程并不是只有sleep会切换进程,进程中途随时可能发生切换,写sleep只是保证发生切换进行验证

5.1 Principles of Concurrency(并发原则)

多个程序交替进行:起始时间和终止时间重合就是并发,不需要多核CPU的并行

并发发生在三种情况:

  1. Multiple applications(多应用程序)

  2. Structured application(结构化应用程序)

    部分的程序(被分割)可以被设计为一系列并发的进程

  3. Operating-system structure(操作系统结构)

    操作系统本身就是一系列的进程和线程

5.1.1 simple example

example1:两个进程同时执行下面的方法

void echo(){
	chin = getchar();
	chout = chin;
	putchar(chout);
}

问题:process1输入完成后,交给了process2,process2覆写了chin并输出,控制权交还给process1之后,输出的值是错的

两个进程共用了chin这个全局变量:解决方法:一次只允许一个进程进入echo,只有运行结束之后才能使另一个进程进入

Example2 : allocate(分配) pid for two new processes when call fork()

给两个不同的进程进行分配pid

new_pid = next_pid++;
//next_pid is a global variable, whose value is now 100
LOAD next_pid Reg1

STORE Reg1 new_pid

INC Reg1           // 进程号++

STORE Reg1 next_pid

两个进程在执行同一段代码

capture_20200929193905742

同理:process1的pid分配时,next_pid虽然被process2覆写了,因为进程切换会被切换而保存

和example1的区别就是一个是全局变量,一个是局部变量

5.1.2 race condition(竞争条件)

竞争条件发生在多个进程同时读写数据,其最终结果取决于多个进程的指令执行顺序

example1中,P1和P2同时竞争全局变量chin,竞争失败者决定a的最终值

进程之间的资源竞争:部分关键词

image-20200929195901092
  1. 互斥(mutual exclusion):两个或者多个进程同时访问不可共享的资源(I/O设备)
  2. 死锁(deadlock):每个进程都需要访问两个不可共享的资源才能执行,R1给P1,R2给P2;两个进程都在等待对方释放资源,自己无法执行,但自身在执行完毕之前都不会释放资源
  3. 活锁(livelock):两个进程同样是访问两个临界资源,但两个进程同时让出了自己的资源给对方进行执行(又周期性拿起资源),两个进程都不执行
  4. 饥饿(starvation):三个进程周期性访问同一个资源,P1执行完毕之后R被分配给P3,P3执行完毕后R被分配给P1,P2被无限延迟
  5. 临界资源:不能共享的资源,临界区:使用临界资源的程序

进程之间的交互

85B72680DA78FB91BDE678A860AC1120

可重用资源:包括I/O设备,内存访问权限等

可消耗资源:一次性资源

5.1.3 different concern

Programmer Concerns

  1. Sharing of global resources
  2. Operating system managing the allocation of resources optimally
  3. Difficult to locate programming errors

Operating System Concerns

  1. 监控不同进程(通过PCB)
  2. Allocate and deallocate resources(分配和释放资源)
  3. Protect data and resources
  4. Output of process must be independent of the speed of execution of other concurrent processes
Requirements for Mutual Exclusion(互斥的要求)
  1. 一次只允许一个进程进入临界区,忙则等待
  2. 阻塞于临界区外的进程不能干涉其它进程
  3. 不会发生饥饿和死锁,有限等待
  4. 没有进程处于临界区,任何需要进入临界区的进程必须立即进入
  5. 对相关进程的执行速度和处理器数量没有任何要求
  6. 一个进程驻留在临界区的时间必须是有限的
image-20200929205355000

.entercritical:进入临界区 .exitcritical:退出临界区

5.2 互斥:硬件的支持
5.2.1 中断禁用

在临界区当中的进程不能够被中断,则可保证临界区互斥

disadvantage:

  1. 处理器将被限制为交替执行程序
  2. 当计算机包括多个内核的情况下,则不能保证互斥
image-20200929205630442

进入临界区,关闭中断;离开临界区,开启中断

CPU 内部 PSW 寄存器,使用:

STI 使IF置“1”,即开放中断。

CLI 使IF清“0”,即关闭中断

Linux 内核使用 cli()和sti()

5.2.2 专用机器指令(均为原子操作)

在硬件级别上,对存储单元的访问排斥对相同单元的其他访问(编写特殊的指令,在这些指令执行的过程当中,不接受任何中断)以指令为基本单位

example1:比较和交换指令(作为原子指令:不接受任何的中断)

int compare_and_swap(int *word, int testval, int newval){
	int oldval;
	oldval = *word;
	if(oldval == testval)
		*word = newval;
	return oldval;
}
// 方法返回0表示当前临界资源空闲,返回1表示临界区中有进程
image-20200929211538812
  1. parbegin表示n个进程同时并发
  2. 第一个进入compare_and_swap的进程发现bolt=0,会将bolt设置为1,他的compare_and_swap返回值为0,跳过while循环
  3. 其他的进程因为bolt被设置为1,compare_and_swap返回值永远是1,直到第一个进程结束了critical section将bolt重新设置为0

example2: exchange指令 单条汇编语言即可实现

void exchange(int register, int memory) {
	int temp;
	temp = memory;
	memory = register;
	register = temp;
}
image-20200929212030717
  1. key是局部变量,bolt是全局变量
  2. 第一个进入的进程将bolt和key1 进行了交换,bolt被设置为1,key1 被设置成0,进入临界区
  3. 剩余的进程,创建了keyi 之后,bolt=1,所以keyi 无论怎样交换都等于1,进入while区域
  4. 直到第一个进程结束对临界区的占有,将bolt设置为0,将有一个进程完成交换,将key设置为0,脱离while区域

忙等待:除了进入临界区的进程之外,剩余的进程只能不停的while循环

Disadvantages

  1. Busy-waiting(忙等待) consumes processor time

  2. Starvation(饥饿) is possible when a process leaves a critical section and more than one process is waiting(有多个进程在等待,某些进程可能会被无限禁止)

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

example3

boolean testset (int i) {
	if (i == 0) {
		i = 1;
		return true;
	}
	else {
		return false;
	}
}
image-20200930094344454
  1. 第一个进入的进程,发现bolt=0,testset将bolt设置为1,并返回true,离开循环
  2. 其他的进程发现bolt为1,进入循环,忙等待
5.3 software approach
5.3.1 Dekker 算法

int turn =0;//turn0 P0进入,1则P1进入

while(1){
while(turn != 0)  ;
Critical section
turn = 1;}
while(1){
while(turn != 1)  ;
Critical section
turn = 0;}

P1需要P0进程结束,将turn设置为1后才能执行

int flag[2]={0,0};//flag[i] =1;进程i意图进入

while(1){
flag[0]=1while(flag[1] == 1)  ;
Critical section
flag[0]=0;}
while(1){
flag[1]=1while(flag[0]= 1)  ;
Critical section
flag[1] = 0;}

会出现死锁的情况,二者都处于while循环当中

image-20200930103008321

turn实现互斥,flag防止出现死锁

  1. P0进入之后,将flag[0] 设置为true,假设turn ==1 表示临界区中已经有人
  2. P1进入之后的方式相同
5.3.1 Peterson 算法
image-20200930102948454
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值