📚 Operating System Fundamentals: Processes, Scheduling and Concurrency | 操作系统基础:进程、调度与并发
An operating system (OS) acts as the bridge between hardware and application software. For any programmer writing code that interacts with the system, understanding how the OS manages processes, schedules CPU time, and handles concurrency is essential. This article explores the core concepts every A-Level programmer needs to know about operating systems, focusing on processes, scheduling algorithms, concurrency issues, and memory management.
操作系统(OS)充当硬件与应用软件之间的桥梁。对于任何编写与系统交互代码的程序员来说,理解操作系统如何管理进程、调度 CPU 时间以及处理并发至关重要。本文探讨每个 A-Level 程序员都需要掌握的操作系统核心概念,重点关注进程、调度算法、并发问题以及内存管理。
1. What is a Process? | 什么是进程?
A process is a program in execution. While a program is a passive collection of instructions stored on disk, a process is an active entity with its own program counter, registers, and memory allocation. When you run an application, the OS creates a process for it, allocating resources like CPU time, memory space, and I/O devices.
进程是正在执行的程序。程序是存储在磁盘上的一组被动指令,而进程是一个活动实体,拥有自己的程序计数器、寄存器和内存分配。当你运行一个应用程序时,OS 会为其创建一个进程,并分配 CPU 时间、内存空间和 I/O 设备等资源。
Each process has its own address space, which includes code, data, heap, and stack segments. The OS ensures isolation between processes so that one process cannot accidentally corrupt another’s memory. This isolation is fundamental for security and stability.
每个进程拥有自己的地址空间,包括代码段、数据段、堆和栈段。OS 确保进程之间的隔离,使一个进程不会意外破坏另一个进程的内存。这种隔离对于安全性和稳定性至关重要。
2. Process States and Transitions | 进程状态与转换
A process can exist in several states during its lifecycle: New, Ready, Running, Waiting (or Blocked), and Terminated. When a process is first created, it is in the New state. Once admitted to the system, it moves to the Ready state, waiting for CPU assignment. When the scheduler dispatches it, the process enters the Running state.
进程在其生命周期中可以存在多种状态:新建(New)、就绪(Ready)、运行(Running)、等待(或阻塞,Waiting/Blocked)和终止(Terminated)。当进程首次创建时,处于新建态。一旦被系统接纳,就会转到就绪态,等待 CPU 分配。当调度程序分派它时,进程进入运行态。
If a running process needs to wait for an event (e.g., I/O completion), it moves to the Waiting state. After the event occurs, it returns to Ready. When execution finishes, it becomes Terminated. These transitions are managed by the OS using process control blocks.
如果运行中的进程需要等待某个事件(如 I/O 完成),它会转移到等待态。事件发生后,它返回就绪态。当执行完成时,则变为终止态。这些状态转换由 OS 通过进程控制块(PCB)管理。
3. Process Control Block (PCB) | 进程控制块
The Process Control Block (PCB) is a data structure maintained by the OS for each process. It contains all the information needed to manage the process, including: process ID, program counter, register values, memory limits, list of open files, and CPU scheduling information. The PCB is crucial for context switching.
进程控制块(PCB)是 OS 为每个进程维护的数据结构。它包含管理进程所需的全部信息,包括:进程 ID、程序计数器、寄存器值、内存界限、打开文件列表以及 CPU 调度信息。PCB 对于上下文切换至关重要。
When the CPU switches from one process to another, it saves the current process’s state in its PCB and loads the next process’s state from its PCB. This ensures that the suspended process can resume execution exactly where it left off.
当 CPU 从一个进程切换到另一个进程时,会将当前进程的状态保存在其 PCB 中,并从下一个进程的 PCB 加载状态。这保证了被挂起的进程可以从断点处恢复执行。
4. Context Switching | 上下文切换
Context switching is the mechanism by which the CPU changes from executing one process to another. This involves saving the state of the current process (registers, program counter, stack pointer) into its PCB, selecting the next process from the ready queue, and loading its saved state. Context switching is a pure overhead, as no useful work is done during the switch.
上下文切换是 CPU 从执行一个进程切换到执行另一个进程的机制。它涉及将当前进程的状态(寄存器、程序计数器、栈指针)保存到其 PCB 中,从就绪队列中选择下一个进程,并加载其保存的状态。上下文切换纯粹是开销,因为切换期间没有完成有用的工作。
The time taken for context switching depends on hardware support and the complexity of the OS. Frequent switching can reduce system throughput, so scheduling algorithms aim to minimise unnecessary switches while maintaining responsiveness.
上下文切换所需的时间取决于硬件支持和 OS 的复杂程度。频繁的切换会降低系统吞吐量,因此调度算法旨在最大限度地减少不必要的切换,同时保持响应能力。
5. Scheduling Algorithms: FCFS, SJF, Round Robin | 调度算法:先到先服务、最短作业优先、轮转法
CPU scheduling decides which process in the ready queue gets to run next. Three fundamental algorithms are: First-Come, First-Served (FCFS), Shortest Job First (SJF), and Round Robin (RR). FCFS is the simplest: processes are executed in the order they arrive. Its disadvantage is the convoy effect, where short processes get stuck behind long ones.
CPU 调度决定就绪队列中哪个进程接下来运行。三种基本算法是:先到先服务(FCFS)、最短作业优先(SJF)和轮转法(RR)。FCFS 最简单:进程按到达顺序执行。其缺点是护送效应(convoy effect),即短进程被阻塞在长进程之后。
SJF selects the process with the smallest total CPU burst time. It can be preemptive (Shortest Remaining Time First) or non-preemptive. SJF minimises average waiting time but requires knowledge of future burst times, which is generally impossible. It may also cause starvation of longer processes.
SJF 选择总 CPU 突发时间最短的进程。它可以是抢占式的(最短剩余时间优先)或非抢占式的。SJF 最小化平均等待时间,但需要预知未来的突发时间,这通常是不可能的。它还可能导致长进程饥饿。
Round Robin assigns a fixed time quantum (e.g., 10–100 ms) to each process in a circular order. If a process does not finish within its quantum, it is preempted and placed at the end of the queue. RR provides good response time but performance depends on quantum size: too large reduces to FCFS, too small causes excessive context switching.
轮转法以循环顺序为每个进程分配固定的时间片(如 10–100 毫秒)。如果进程未在时间片内完成,就会被抢占并放到队列末尾。RR 提供良好的响应时间,但性能取决于时间片大小:太大会退化为 FCFS,太小则导致过多的上下文切换。
6. Multilevel Queue and Priority Scheduling | 多级队列与优先级调度
In priority scheduling, each process is given a priority (usually an integer). The CPU is allocated to the highest-priority process. Priorities can be static or dynamic. A major problem is starvation, where low-priority processes may never execute. Ageing – gradually increasing the priority of waiting processes – can solve this.
在优先级调度中,每个进程被赋予一个优先级(通常是一个整数)。CPU 分配给优先级最高的进程。优先级可以是静态的或动态的。一个主要问题是饥饿,低优先级的进程可能永远无法执行。老化(aging)——逐渐提高等待进程的优先级——可以解决这个问题。
Multilevel queue systems partition the ready queue into several separate queues, e.g., foreground (interactive) and background (batch) processes. Each queue may have its own scheduling algorithm. Scheduling between queues is usually fixed-priority preemptive, but time slices can also be allocated among queues (multilevel feedback queue).
多级队列系统将就绪队列分割成几个独立的队列,例如前台(交互式)进程和后台(批处理)进程。每个队列可以有自己的调度算法。队列间调度通常是固定优先级抢占式的,但也可以在队列间分配时间片(多级反馈队列)。
7. Concurrency and Race Conditions | 并发与竞态条件
Concurrency arises when multiple processes or threads execute simultaneously, sharing data. A race condition occurs when the outcome depends on the non-deterministic ordering of execution. For example, two processes reading and writing a shared variable without synchronisation can produce incorrect results.
当多个进程或线程同时执行并共享数据时,就会产生并发。竞态条件(race condition)发生在结果取决于非确定性的执行顺序时。例如,两个进程在没有同步的情况下读写一个共享变量,可能会产生错误的结果。
To illustrate, consider a shared bank balance balance = 1000. If process A reads balance, subtracts 200, and writes back 800, but process B reads balance before A writes back, and also subtracts 300, writing 700, the final balance could be 700 instead of 500. This inconsistency is the race condition.
例如,考虑共享的银行余额 balance = 1000。如果进程 A 读取 balance、减去 200 并写回 800,但进程 B 在 A 写回之前读取 balance,也减去 300 并写回 700,最终余额可能是 700 而不是 500。这种不一致就是竞态条件。
8. Mutual Exclusion: Locks and Semaphores | 互斥:锁与信号量
To prevent race conditions, we must enforce mutual exclusion, ensuring that only one process can access a shared resource at a time. A common mechanism is a lock (mutex). Before entering a critical section – the code segment accessing shared data – a process acquires the lock; afterward it releases it. If the lock is held by another, the process blocks.
为了防止竞态条件,我们必须强制互斥,确保一次只有一个进程可以访问共享资源。一个常见的机制是锁(互斥量,mutex)。在进入临界区——访问共享数据的代码段——之前,进程获取锁;之后释放锁。如果锁被另一个进程持有,则阻塞。
Semaphores generalise locks. A binary semaphore acts as a mutex, while a counting semaphore controls access to a pool of identical resources. Semaphores support two atomic operations: wait (P) and signal (V). They are used in synchronisation problems such as the Producer-Consumer or Readers-Writers problems.
信号量(semaphore)是对锁的泛化。二元信号量相当于互斥量,而计数信号量控制对一组相同资源的访问。信号量支持两个原子操作:wait(P)和 signal(V)。它们用于同步问题,如生产者-消费者问题或读者-写者问题。
9. Deadlock and Prevention | 死锁及其预防
Deadlock occurs when a set of processes are each waiting for a resource held by another process in the set, resulting in all processes being blocked indefinitely. Four necessary conditions must hold simultaneously for deadlock: mutual exclusion, hold and wait, no preemption, and circular wait.
当一组进程中的每个进程都在等待另一个进程持有的资源,导致所有进程被无限期阻塞时,就会发生死锁。死锁发生必须同时满足四个必要条件:互斥、持有并等待、不可抢占和循环等待。
Deadlock prevention aims to break at least one of these conditions. For example, requiring a process to request all resources at before starting eliminates hold-and-wait. Allowing preemption of resources can avoid circular wait. However, prevention can be expensive and reduce resource utilisation.
死锁预防旨在打破这四个条件中的至少一个。例如,要求进程在开始前一次性申请所有资源可以消除持有并等待。允许抢占资源可以避免循环等待。但是,预防可能代价高昂并降低资源利用率。
10. Memory Management: Paging and Segmentation | 内存管理:分页与分段
Memory management is the OS function that allocates and tracks memory for processes. Two common non-contiguous allocation techniques are paging and segmentation. Paging divides physical memory into fixed-size blocks called frames, and logical memory into pages of the same size. A page table maps each process’s pages to frames.
内存管理是 OS 为进程分配和跟踪内存的功能。两种常见的非连续分配技术是分页和分段。分页将物理内存划分为称为帧(frame)的固定大小块,逻辑内存划分为相同大小的页(page)。页表将每个进程的页映射到帧。
Paging eliminates external fragmentation but suffers from internal fragmentation if a process does not use the whole page. Segmentation divides memory into variable-sized logical segments, such as code, data, stack. It matches the programmer’s view but can lead to external fragmentation.
分页消除了外部碎片,但如果进程没有用完整页,就会产生内部碎片。分段则将内存划分为可变大小的逻辑段,如代码段、数据段、栈段。它符合程序员的视角,但可能导致外部碎片。
11. Virtual Memory and Page Replacement | 虚拟内存与页面置换
Virtual memory allows a process to execute even if it is not entirely in physical memory. It separates logical address space from physical memory, enabling larger programs and better multitasking. When a referenced page is not in memory (page fault), the OS loads it from disk, possibly replacing an existing page.
虚拟内存允许进程即使在物理内存中不完全驻留也能执行。它将逻辑地址空间与物理内存分离,从而支持更大的程序并提高多任务处理能力。当引用的页不在内存中时(缺页中断),OS 从磁盘加载该页,并可能替换一个现有页。
Page replacement algorithms decide which page to evict. The optimal algorithm replaces the page that will not be used for the longest time, but it is impractical. FIFO replaces the oldest page but can cause Belady’s anomaly. LRU (Least Recently Used) replaces the most unused page, approximating optimal behaviour.
页面置换算法决定替换哪个页面。最优算法替换未来最长时间不会使用的页面,但不现实。FIFO 替换最早的页面,但可能引发 Belady 异常。LRU(最近最少使用)替换最久未使用的页面,近似于最优行为。
12. Why This Matters for Programmers | 为什么这对程序员很重要
Understanding OS fundamentals helps programmers write efficient, concurrent code. Knowing scheduling policy can influence how you design I/O-bound vs CPU-bound threads. Awareness of race conditions and locking prevents subtle bugs. Memory management concepts inform how you handle data structures and avoid leaks.
理解操作系统的基础知识有助于程序员编写高效、并发的代码。了解调度策略可以影响你如何设计 I/O 密集型和 CPU 密集型线程。对竞态条件和锁的认识可以防止细微的错误。内存管理概念指导你如何处理数据结构并避免内存泄漏。
In languages like C, you directly call malloc and free, whereas in Java or Python, garbage collectors abstract this. However, understanding virtual memory can explain performance anomalies like swapping. Ultimately, the OS is the platform for all your programs – knowing its inner workings makes you a better developer.
在 C 等语言中,你直接调用 malloc 和 free;而在 Java 或 Python 中,垃圾收集器将其抽象化。然而,理解虚拟内存可以解释交换等性能异常。归根结底,操作系统是你所有程序的平台——了解其内部运作会让你成为更好的开发者。
Published by TutorHao | Programming Revision Series | aleveler.com
更多咨询请联系16621398022(同微信)
屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导