跳到主要内容

操作系统

大学计算机科学知识点 7

本主题的视频课程 打开视频页面
6:44

操作系统

操作系统让一个处理器看起来像多台机器。前三个单元讲解处理器所呈现的假象:进程、轮流运行和安全共享。接下来的两个单元讲内存和存储。最后一个单元构建程序与内核之间的屏障。本课程中的每张表、每种交错执行和每次页表遍历都是确定的,所以你可以自己重新计算。

英文讲解 · 可切换中英文字幕

讲义

English

What this course is, and how to use it

This is the seventh course in University Computer Science: operating systems 操作系统. The operating system (OS) is the layer that makes one processor look like many machines. The course covers processes, scheduling, synchronisation, virtual memory, files, and the walls between users.

A limit, stated once: this is a study course, not a degree. The teaching kernel is an original small design. Every scheduling table, interleaving and page-table walk in this handout is fully worked out step by step, so you can check each one yourself.

  • Units 7.1–7.3 share the processor: processes, taking turns, and sharing data safely.
  • Units 7.4–7.5 share memory and storage: address spaces and files.
  • Unit 7.6 is the wall: protection and security.

The habit to build: an operating system is a resource accountant. Every mechanism in this course is a record of who owns what, and whose turn it is.

Processes and threads

Why it matters. A process 进程 is a running program, with its own address space, registers and open files. The first job of the OS is to run hundreds of them on just a few cores.

A state diagram: new to ready (admit), ready to running (dispatch by the scheduler), running to ready (interrupt or time-out), running to blocked (request I/O), blocked back to ready (I/O complete), running to terminated (exit)
A process moves between the new, ready, running, blocked and terminated states

The idea. A process passes through five states 状态:

state meaning
new being created
ready 就绪 could run, waiting only for a processor
running 运行 on a processor now
blocked 阻塞 waiting for I/O or another event
terminated finished

The scheduler moves processes between ready and running, and devices move blocked processes back to ready. A thread 线程 is one flow of execution inside a process. Threads share the address space and files, but each has its own stack and registers.

Process state diagram
Five states, four transitions that matter: dispatch and preempt between ready and running, block on I/O, wake on completion

Why the PCB exists. To pause a process, the OS must save everything that defines it. This record is the process control block 进程控制块 (PCB): register values, the program counter, a pointer to the page table, and the open files. A context switch 上下文切换 is exactly this save and restore. With our course timings, saving and restoring $2000$ bytes of state at $2$ GB/s costs $1$ µs. On top of that, the caches now hold the wrong data, which slows the next part of the run. Switching between threads of one process does not change the address space (it is shared), so it is cheaper; switching processes pays the full cost.

Worked example 1: the journey of a page fault.

  1. Process A is running and has a page fault: running → blocked (it waits for the disk).
  2. The scheduler dispatches process B.
  3. The disk finishes: A → ready.
  4. Later, A → running again, and the instruction that faulted is run again from the start.

That is four state changes, two processes and no lost work. Being able to restart an instruction is what makes it safe to pause a process at all.

Worked example 2: threads or processes. A web server starts one thread for each connection. The threads share the cache and the settings, and creating and switching a thread costs about $50$ µs. Doing the same with processes costs about $500$ µs, mostly to set up a new page table (copy-on-write avoids copying the memory itself), and each process fills its own caches. Sharing is the whole point of threads, and, as unit 7.3 shows, also their whole danger.

Common mistakes.

  • Mixing up blocked and ready. A blocked process waits for a device; a ready process waits only for a processor.
  • Thinking a crash in one thread stays in that thread. It ends the whole process, because there is one address space.
  • Counting the cost of a context switch as processor time only. Filling the caches again usually costs more.

Summary. Process = address space + PCB; a thread = its own stack and registers inside a process. Five states, with dispatch, preempt, block and wake. Switching threads is cheaper because the address space is shared.

Scheduling

Why it matters. When there are more processes than cores, something must decide whose turn it is. The scheduler does this, and its policy shows what the system values most: throughput, fairness or quick response. You cannot have all three at once.

Two timelines of the same three jobs: first-come-first-served runs the long job first and the short jobs wait behind it, while shortest-job-first runs the short jobs first and cuts the average waiting time from 6.7 to 2.7 units
The same work in a different order: shortest-job-first gets the short jobs out of the way, so most jobs wait less, at the risk of a long job waiting for ever

The idea. Our teaching policies:

  • FCFS 先来先服务 (first come, first served);
  • SJF 短作业优先 (shortest job first);
  • round robin 时间片轮转 (RR), with a time slice (quantum) of $q = 2$;
  • priority with aging (a waiting process slowly gains priority).

A Gantt chart 甘特图 shows who ran when.

Scheduling Gantt timelines
One arrival set, three policies: SJF finishes the short jobs first, RR slices everyone in turn

The two measures.

  • Turnaround time 周转时间 $=$ finish time $-$ arrival time.
  • Waiting time 等待时间 $=$ turnaround time $-$ burst (the run time the process needs).

The course set: all four processes arrive at time $0$, with bursts P1 $= 7$, P2 $= 4$, P3 $= 1$ and P4 $= 4$.

policy order finish times average turnaround
FCFS P1, P2, P3, P4 $7, 11, 12, 16$ $46/4 = \mathbf{11.5}$
SJF P3, P2, P4, P1 $1, 5, 9, 16$ $31/4 = \mathbf{7.75}$
RR ($q = 2$) see below P3 $5$, P2 $11$, P4 $13$, P1 $16$ $45/4 = \mathbf{11.25}$

The RR trace is P1 P1 | P2 P2 | P3 | P4 P4 | P1 P1 | P2 P2 | P4 P4 | P1 P1 | P1. The same jobs give three different answers under three policies. SJF has the best average. RR is best for the longest wait before a process first runs: every process starts by time $5$, while under SJF P1 first runs at time $9$.

Worked example 1: the convoy effect. Under FCFS, a long job (P1, burst 7) arrives first and everything queues behind it. P3 waits $11$ units for $1$ unit of work. SJF would run P3 first, with a wait of $0$. This convoy is the typical failure of FCFS when interactive users are mixed in.

Worked example 2: choosing the quantum. With $q = 2$, our trace has $9$ run segments, so $8$ slice boundaries. With $q = 7$, every job finishes in its first slice, and RR becomes FCFS: fewer switches, but short P3 waits $11$ before it runs. The rule:

  • a very large $q$ turns RR into FCFS;
  • a very small $q$ spends the processor on switching. With a switch cost of $1$ µs, a $2$ ms quantum wastes $0.05\%$; a $20$ µs quantum wastes $5\%$.

Common mistakes.

  • Averaging finish times instead of turnaround times. They are equal here only because everything arrives at $0$.
  • Forgetting that SJF needs to know the bursts in advance. In practice it is a model; schedulers such as MLFQ estimate it.
  • Thinking a small quantum is faster. Switching is work, not progress.

Summary. Turnaround = finish − arrival. SJF gives the lowest average turnaround of the non-preemptive policies. RR gives up some average performance for fairness and quick response; the quantum sets the balance.

Synchronisation

Why it matters. Threads share memory, and sharing without synchronisation damages data. The lost update is one of the smallest bugs in computing, and one of the most expensive.

The idea. The classic race: two threads both run counter = counter + 1, starting from counter = 5. Each thread reads, adds 1 and writes. With the interleaving 交错 "read 1, read 2, write 1, write 2", both threads read $5$ and both write $6$. The result is $6$, not $7$: one update is lost. The fix is mutual exclusion 互斥: a lock 锁 makes the read-add-write happen as one indivisible step.

Race interleaving and lock
Unlocked: the interleaving reads 5 twice and writes 6 twice — one increment vanishes; locked: the second thread waits

What a correct lock must guarantee. Three conditions:

  1. mutual exclusion: only one thread is inside the critical section;
  2. progress: if the section is free, some waiting thread gets in;
  3. bounded waiting: no thread waits for ever.

Peterson's algorithm meets all three for two threads, using two flags and a turn variable. An atomic test-and-set instruction can implement mutual exclusion, but a basic test-and-set spinlock does not guarantee bounded waiting. Both of these spin 自旋: the waiting thread keeps the processor busy checking. Semaphores and mutexes add an OS queue, so a waiting thread sleeps instead. This is why real systems use both layers.

Worked example 1: how low can the count go? Two threads each increment a shared counter $4$ times, with no lock. The worst case:

  1. A reads $0$ and pauses.
  2. B runs three full increments: the counter is $3$.
  3. A writes $1$, wiping out B's work.
  4. B reads $1$ and pauses.
  5. A runs its last three increments: the counter is $4$.
  6. B writes $2$.

The counter ends at $\mathbf{2}$: six of the eight increments are lost. A final value of $1$ is impossible, because a thread's next read always comes after its own last write. Checking every interleaving shows that every final value from $2$ to $8$ can happen. The race does not fail loudly; it quietly counts too low. With a lock, the result is always $8$.

Worked example 2: the four conditions for deadlock. Two threads and two locks, L1 and L2: A holds L1 and wants L2; B holds L2 and wants L1. Deadlock needs all four of these:

  1. mutual exclusion;
  2. hold and wait;
  3. no preemption (a lock cannot be taken away);
  4. circular wait.

Break any one and deadlock cannot happen. The usual one to break is circular wait: always take the locks in a fixed order (L1 before L2).

Common mistakes.

  • "Fixing" a race by adding sleeps. This makes the window smaller but does not close it.
  • Taking locks in different orders in different threads. That is the recipe for deadlock.
  • Thinking a single-core machine is safe. A thread can still be paused between the read and the write.

Summary. Races come from read-add-write steps that can be interrupted. Locks make them indivisible, at the cost of waiting. Correctness needs exclusion, progress and bounded waiting. Break one of the four deadlock conditions; ordering the locks is the cheapest.

Virtual memory

Why it matters. Every process believes it owns the whole address space, while all of them share one physical RAM. This is the OS's greatest illusion. It is the source of much of its speed, and of some of its worst failures.

Logical-memory pages mapped through a page table to non-contiguous physical-memory frames
Paging maps each page of logical memory to a frame of physical memory

The idea.

  • A virtual address 虚拟地址 is split into a page number (VPN) and an offset.
  • The page table 页表 maps each virtual page to a physical frame 物理页框, with one entry per page.
  • The TLB 快表 caches recent translations.

Our course machine has $16$-bit virtual addresses and $256$-byte pages, so $256$ virtual pages. Physical addresses are $12$ bits, so there are $16$ frames.

Page-table mapping
Virtual page numbers through the page table to frames: VPN 2 to frame 5, VPN 4 to frame 9, VPN 2 again hits the TLB

The size of the illusion.

  1. A page is $256 = 2^8$ bytes, so the offset is $8$ bits and the VPN is $16 - 8 = 8$ bits: $256$ pages.
  2. A process can address $2^{16}$ bytes $= 64$ KiB, but there are only $16$ physical frames ($16 \times 256 = 4$ KiB).
  3. Each page-table entry holds a frame number ($4$ bits), a valid bit and a dirty bit: $256 \times 6 = 1536$ bits for the whole table.

Two processes can each have all $256$ virtual pages. Promising more memory than exists costs nothing until a process touches a page that is not in memory.

Worked example 1: the walk, then the hit. Address $0x0204$: the offset is $0x04$ (the low 8 bits) and the VPN is $0x02$.

  1. First access: TLB miss, so read the page table. VPN 2 → frame 5. Physical address $= 5 \times 256 + 4 = 0x0504$. The TLB now stores VPN 2.
  2. Next, address $0x0210$: the same VPN $2$, so a TLB hit. Physical address $0x0510$, with no table walk.

With a 10-entry TLB, a loop over 8 pages that makes $8000$ accesses misses only $8$ times (the first touch of each page). That is a $99.9\%$ hit rate (with LRU replacement).

Worked example 2: a page fault and its cost. Address $0x0400$ has VPN $4$, and its table entry is invalid, so this is a page fault 缺页.

  1. The process is blocked.
  2. The OS chooses a victim page. With LRU, it is the page in frame $9$, which is dirty, so it is written back to disk first.
  3. VPN 4 is read into frame $9$.
  4. The page table and the TLB are updated.
  5. The instruction is run again.

Cost model: a TLB hit costs $1$ ns, a table walk $10$ ns, and a fault with a disk read $5$ ms. Even one fault per million accesses adds $5\,\mathrm{ms} / 10^6 = 5$ ns to every access on average. The hierarchy can cope with rare faults, not frequent ones.

Common mistakes.

  • Working out the physical address without multiplying the frame number by the page size.
  • Forgetting that a dirty victim doubles the cost of a fault (one write, one read).
  • Thinking every page fault is either a disk read or an illegal access. A valid page that is not in memory may be loaded; a new page may be allocated; and an access that breaks the protection rules may end the process.

Summary. VPN + offset → page table → frame + offset. The TLB makes table walks rare. Page faults make it safe to promise more memory than exists, at disk prices. The valid and dirty bits are the extra notes in the record.

File systems

Why it matters. Files outlast the process that made them. How they are laid out on disk decides how fast they are, how reliable they are, and what a crash destroys.

An opened 3.5-inch hard disk drive: a shiny circular platter with the actuator arm and read/write head resting over it
An opened hard disk: the actuator arm carries the read/write head over a platter
Two chains of steps: direct access hashes the key to an address, seeks straight to it and reads or writes the record; sequential access opens the file, reads records one at a time from the start and compares keys until the record is found or the end of the file is reached
The two access methods as procedures: direct access computes where to look; sequential access looks everywhere in turn

The idea. Our teaching disk has $32$ blocks of $1$ KiB.

  • An inode 索引节点 holds a file's metadata, $4$ direct pointers to data blocks, and one indirect pointer (to a block that holds $256$ more pointers).
  • A directory is a file of entries, each mapping a name to an inode.
  • FAT 链表式分配 (file allocation table) instead links each block of a file to the next one.
File system layout
Directory entries to inodes to blocks: direct pointers first, the indirect block for big files, the free list on the side

The largest possible file. The pointers set the limit:

$$\text{max size} = (\text{direct pointers} + \text{pointers per block}) \times \text{block size}$$
  • With $4$ KiB blocks holding $1024$ pointers each: $(4 + 1024) \times 4\,\mathrm{KiB} \approx 4$ MiB.
  • In our teaching design ($1$ KiB blocks, $256$ pointers), the inode addressing limit is $(4 + 256) \times 1\,\mathrm{KiB} = 260$ KiB, but the 32-block disk cannot hold a file that large.

Access cost: a block with number $n < 4$ costs one disk read (the inode is cached); a block with $n \ge 4$ also needs the indirect block to be read. When blocks are linked in a chain, a file can be spread over the disk, so reading it in order needs many seeks. Keeping a file in one piece is a speed decision, not a correctness one.

Worked example 1: reading block 6 of /notes/x. The directory lookup finds the inode (it is cached). Block $6$ is beyond the four direct pointers, so the OS reads the indirect block, takes its pointer number $6 - 4 = 2$, and then reads the data block. That is two disk reads for one block of the file; block $2$ would have cost one. Reading a $100$-block file from start to end costs, at best, $100$ data reads $+ 1$ indirect read.

Worked example 2: what does a crash destroy? Adding to a file writes three things: the data block, the bit in the free list, and the new size in the inode. If the system crashes between these writes, the order decides the damage:

  • data first, inode last: nothing is lost except some space (a block is marked used but belongs to no file);
  • inode first, data last: the inode reports a size that includes a block of garbage, so reads return rubbish.

Journaling 日志 first writes a note of what it is about to do, and replays the note after a crash. This is why modern file systems accept a small extra cost on every write: it keeps them consistent after a crash.

Common mistakes.

  • Forgetting that a directory is itself a file, so every lookup is a read.
  • Thinking the indirect pointer is free. Following it is a disk read.
  • Thinking deletion erases the data. It clears the pointers; the data stays until the block is reused.

Summary. Directory → inode → direct and indirect pointers → blocks. Maximum size $= (\text{direct} + \text{pointers per block}) \times \text{block size}$. The write order decides what a crash destroys; journaling keeps the file system consistent.

Protection and security

Why it matters. Everything above assumed that programs cooperate. Protection is the wall, built by the hardware and the OS together, that makes this assumption unnecessary. Security is the work of keeping that wall standing.

A black hardware security key on a white background, with a round gold touch sensor in the middle and a gold USB connector at one end
A hardware security key stores a secret key to prove who you are

The idea. There are two rings 特权级 (privilege levels):

  • user mode runs application code;
  • kernel mode 特权模式 runs the OS, and can use devices and change page tables.

The only doors through the wall are system calls 系统调用, and a mode bit in the processor enforces this.

Privilege boundary
User code crosses to the kernel only through the syscall door; the kernel validates everything at the boundary

The principle of least privilege. Every mechanism above can be attacked: the scheduler's queues, the bits in the page table, the file metadata. Least privilege 特权最小化 gives each process only what it needs:

  • page tables do this for each process (unit 7.4);
  • file permissions do it for each user: read, write and execute, for the owner, the group and others, which is $3 \times 3 = 9$ bits;
  • capabilities do it for each object.

A smaller privileged part of the system means a smaller target for bugs. This is why microkernels and sandboxed browsers exist.

Worked example 1: one system call, crossing the wall. A user program calls open("/notes/x"):

  1. A trap instruction switches the mode bit, saves the user registers and jumps to a fixed address in the kernel.
  2. The kernel checks the path and the permissions, and creates a file descriptor.
  3. It returns, and the mode bit switches back.

That is two crossings per system call, at about $100$ ns each. A program that makes $10^6$ system calls pays $10^6 \times 200$ ns $= 0.2$ s. This is why libraries buffer data and group calls together.

Worked example 2: the confused deputy. An unprivileged user asks a privileged printer program to print /salary.db. The printer program opens the file with its own authority, not the user's. It is a "deputy" that is confused about whose wishes it is carrying out. The fix is to pass capabilities (already-open file descriptors) instead of names: the deputy can then only use what it was given. Every door in the wall must check identity at every crossing; otherwise the wall itself becomes the weapon.

Common mistakes.

  • Calling security one layer. It is a property of every layer.
  • Checking permissions when a file is opened but not when it is used (TOCTOU: time of check to time of use).
  • Trusting a pointer because it came from user space. Always check at the boundary.

Summary. The mode bit builds the wall, and system calls are its doors. Least privilege decides how much each process can reach. Check every crossing, and pass capabilities, not names.

词汇
English 中文 拼音
operating systems/ˈɒpəreɪtɪŋ ˈsɪstəmz/ 操作系统 cāo zuò xì tǒng
process/ˈprəʊses/ 进程 jìn chéng
states/steɪts/ 状态 zhuàng tài
ready/ˈredi/ 就绪 jiù xù
running/ˈrʌnɪŋ/ 运行 yùn xíng
blocked/blɒkt/ 阻塞 zǔ sè
process control block/ˈprəʊses kənˈtrəʊl blɒk/ 进程控制块 jìn chéng kòng zhì kuài
context switch/ˈkɒntekst swɪtʃ/ 上下文切换 shàng xià wén qiè huàn
thread/θred/ 线程 xiàn chéng
FCFS/ˌef siː ef ˈes/ 先来先服务 xiān lái xiān fú wù
SJF/ˌes dʒeɪ ˈef/ 短作业优先 duǎn zuò yè yōu xiān
round robin/raʊnd ˈrɒbɪn/ 时间片轮转 shí jiān piàn lún zhuàn
Gantt chart/ɡænt tʃɑːt/ 甘特图 gān tè tú
turnaround time/ˈtɜːnəraʊnd taɪm/ 周转时间 zhōu zhuǎn shí jiān
waiting time/ˈweɪtɪŋ taɪm/ 等待时间 děng dài shí jiān
interleaving/ˌɪntəˈliːvɪŋ/ 交错 jiāo cuò
mutual exclusion/ˈmjuːtʃuːəl eksˈkluːʒn/ 互斥 hù chì
lock/lɒk/ 锁 suǒ
spin/spɪn/ 自旋 zì xuán
virtual address/ˈvɜːtʃuːəl əˈdres/ 虚拟地址 xū nǐ dì zhǐ
page table/peɪdʒ ˈteɪbl/ 页表 yè biǎo
physical frame/ˈfɪzɪkl freɪm/ 物理页框 wù lǐ yè kuāng
TLB/ˌtiː el ˈbiː/ 快表 kuài biǎo
page fault/peɪdʒ fɒlt/ 缺页 quē yè
inode/ɪˈnəʊd/ 索引节点 suǒ yǐn jié diǎn
journaling/ˈdʒɜːnəlɪŋ/ 日志 rì zhì
rings/rɪŋz/ 特权级 tè quán jí
kernel mode/ˈkɜːnl məʊd/ 特权模式 tè quán mó shì
system call/ˈsɪstəm kɔːl/ 系统调用 xì tǒng diào yòng
least privilege/liːst ˈprɪvɪlɪdʒ/ 特权最小化 tè quán zuì xiǎo huà
FAT/ˌef eɪ ˈtiː/ 链表式分配 liàn biǎo shì fēn pèi

该知识点的互动课程

逐步完成,配合即时检查练习。

更多 大学计算机科学 知识点

登录或创建账户

IGCSE, A-Level & AP