📚 Conflict in Concurrency: Race Conditions and Deadlock | 并发中的冲突:竞态条件与死锁
In computer systems, multiple processes or threads often need to share resources such as memory, files or I/O devices. Without careful coordination, these interactions can lead to conflicts that cause unpredictable behaviour, corrupted data or complete system standstill. Understanding the nature of these conflicts and the techniques to manage them is a central topic in the A-Level Computer Science syllabus, particularly within the Edexcel specification.
在计算机系统中,多个进程或线程经常需要共享内存、文件或输入输出设备等资源。如果没有精心的协调,这些交互就会导致冲突,产生不可预测的行为、数据损坏或整个系统停滞。理解这些冲突的本质以及管理冲突的技术,是 A-Level 计算机科学教学大纲(尤其是 Edexcel 考试局)中的核心主题。
1. What is Conflict in Concurrent Systems? | 并发系统中的冲突是什么?
Conflict arises when two or more concurrent activities interfere with each other by attempting to access shared resources in an uncontrolled manner. If the final outcome depends on the precise order of execution of these activities, we have a race condition – a type of conflict that makes the system’s state unpredictable.
当两个或多个并发活动试图以不受控制的方式访问共享资源而相互干扰时,就会产生冲突。如果最终结果取决于这些活动的精确执行顺序,我们就遇到了竞态条件——一种使系统状态不可预测的冲突类型。
At the hardware level, conflicts can occur when two processors try to write to the same memory location simultaneously. At the operating system level, conflicts emerge during process scheduling, file system updates or device handling. In all cases, the root cause is a lack of proper synchronisation.
在硬件层面,当两个处理器试图同时写入同一内存位置时会发生冲突。在操作系统层面,冲突出现在进程调度、文件系统更新或设备处理期间。所有情况的根本原因都是缺乏适当的同步。
2. Race Conditions Explained | 竞态条件解析
A race condition occurs when the behaviour of software depends on the relative timing of events such as thread execution order. Consider two threads that both increment a shared counter. Without synchronisation, both might read the same initial value, increment it separately, and write back, resulting in only one effective increment instead of two. This leads to lost updates and inconsistent data.
当软件的行为依赖于线程执行顺序等事件的相对时序时,就会发生竞态条件。设想两个线程都对一个共享计数器进行递增操作。如果没有同步,两者可能读取相同的初始值,分别递增后再写回,导致实际上只完成了一次递增而不是两次。这会引起更新丢失和数据不一致。
Race conditions are notoriously difficult to debug because they are non-deterministic: the bug may appear only under specific timing conditions, which can be rare. Therefore, operating systems and programming languages provide synchronisation mechanisms to eliminate races by enforcing orderly access to shared resources.
竞态条件因难以调试而闻名,因为它们是*非确定性的*:这个错误可能只在特定的时序条件下才出现,而这种条件又很罕见。因此,操作系统和编程语言提供了各种同步机制,通过强制对共享资源进行有序访问来消除竞态。
3. The Critical Section Problem | 临界区问题
A critical section is a code segment that accesses shared resources and must not be executed by more than one process or thread at a time. The critical section problem is the challenge of designing a protocol that guarantees mutual exclusion, progress and bounded waiting.
临界区是一段访问共享资源的代码,同一时刻不能被多个进程或线程执行。临界区问题就是要设计一个协议,以保证*互斥*、*前进*和*有限等待*。
The two classic solutions for two-process systems are Peterson’s algorithm and Dekker’s algorithm. Peterson’s algorithm uses two shared flags and a turn variable to ensure that only one process enters the critical section at any time. Although these algorithms are mainly of theoretical importance today, they illustrate the fundamental principles of conflict avoidance.
针对双进程系统的两个经典解决方案是 Peterson 算法和 Dekker 算法。Peterson 算法使用两个共享标志和一个转向变量,保证在任何时刻只有一个进程进入临界区。尽管这些算法在今天主要具有理论意义,但它们阐明了避免冲突的基本原理。
4. Mutual Exclusion with Hardware Support | 借助硬件支持的互斥
Modern processors often provide atomic instructions such as Test-and-Set (TSL) or Compare-and-Swap (CAS) that can be used to build simple spinlocks. A spinlock repeatedly tests a lock variable until it becomes available. While effective for short critical sections, spinlocks waste CPU cycles when the lock is held for longer periods.
现代处理器通常提供原子指令,如 Test-and-Set(TSL)或 Compare-and-Swap(CAS),可以用来构建简单的自旋锁。自旋锁反复测试一个锁变量,直到它变为可用。虽然自旋锁对短临界区有效,但当锁被长时间持有时会浪费 CPU 周期。
In practice, operating system kernels use higher-level primitives that combine atomic hardware operations with process blocking. This avoids busy-waiting and allows the CPU to schedule other useful work while a process waits for a resource. Such primitives form the basis of semaphores and mutexes.
在实践中,操作系统内核使用更高级的原语,将原子硬件操作与进程阻塞结合起来。这样避免了忙等待,使 CPU 能够在进程等待资源时调度其他有用的工作。这些原语构成了信号量和互斥量的基础。
5. Semaphores and Mutexes | 信号量与互斥量
A semaphore is an integer variable that is accessed only through two atomic operations: wait (often called P) and signal (V). A counting semaphore can control access to a resource with multiple instances, while a binary semaphore behaves like a mutex and can be used to protect a single critical section.
信号量是一个整型变量,只能通过两个原子操作来访问:wait(常称为 P 操作)和 signal(V 操作)。计数信号量可以控制对具有多个实例的资源的访问,而二进制信号量行为类似于互斥量,可用于保护单个临界区。
A mutex (mutual exclusion) is a locking mechanism that enforces exclusive access to a resource. Unlike semaphores, which can be released by any thread, a mutex is typically owned by the thread that locks it, and only that thread can unlock it. This ownership model helps avoid accidental misuse.
互斥量(互斥)是一种强制对资源进行排他性访问的锁机制。与可被任何线程释放的信号量不同,互斥量通常由锁定它的线程拥有,并且只有该线程才能解锁。这种所有权模型有助于避免意外误用。
6. Deadlock: The Ultimate Conflict | 死锁:终极冲突
Deadlock is a state where a set of processes are each waiting for a resource held by another process in the set, causing all to remain blocked indefinitely. It represents a severe form of conflict where the system cannot make any progress without external intervention.
死锁是这样一种状态:一组进程中的每一个都在等待该组中另一个进程占有的资源,导致所有进程无限期地阻塞。这是一种严重的冲突形式,系统在没有外部干预的情况下无法取得任何进展。
Deadlock can only occur if four necessary conditions hold simultaneously: mutual exclusion, hold and wait, no preemption, and circular wait – known as the Coffman conditions. Breaking any one of these conditions can prevent deadlock.
死锁只有在四个必要条件同时成立时才可能发生:互斥、占有并等待、不可剥夺和环路等待——即著名的 Coffman 条件。打破其中任何一个条件就能预防死锁。
7. Deadlock Prevention | 死锁预防
Prevention strategies aim to negate at least one of the Coffman conditions. For example, we can eliminate mutual exclusion by using shareable resources when possible, though not all resources can be made shareable. We can eliminate hold and wait by requiring a process to request all needed resources before starting execution.
预防策略旨在否定至少一个 Coffman 条件。例如,我们可以通过在可能的情况下使用可共享资源来消除互斥条件,尽管并非所有资源都能实现共享。我们可以通过要求进程在开始执行之前就请求所有需要的资源来消除占有并等待。
To break the no preemption condition, the operating system can forcibly take back a resource from a waiting process. Finally, to break circular wait, a total ordering can be imposed on resource types, and processes must request resources in an increasing order. Each approach has performance and usability trade-offs.
为了打破不可剥夺条件,操作系统可以从等待进程中强制收回资源。最后,为了打破环路等待,可以为资源类型规定一个全序,进程必须按升序申请资源。每种方法都有性能和可用性方面的权衡。
8. Deadlock Avoidance and the Banker’s Algorithm | 死锁避免与银行家算法
Deadlock avoidance is a dynamic approach where the system uses resource-allocation-state information to decide whether granting a request could lead to an unsafe state. An unsafe state is one in which deadlock is not inevitable but cannot be ruled out. The system thus allows requests only if the resulting state is safe.
死锁避免是一种动态方法:系统利用资源分配状态信息来决定批准某个请求是否会导致不安全状态。不安全状态是指死锁虽非必然发生但不能被排除的状态。因此,系统只有在结果状态安全的情况下才允许请求。
The classic avoidance algorithm for resources with multiple instances is the Banker’s algorithm. It operates by testing whether, after granting a request, the system can still finish all processes in some order using the currently available resources and the maximum needs declared in advance. The algorithm is a practical demonstration of safe-state detection.
适用于具有多个实例资源的经典避免算法是银行家算法。其工作原理是:测试在批准某个请求后,系统是否仍能利用当前可用资源和预先声明的最大需求,按某种顺序完成所有进程。该算法是安全状态检测的实际示范。
9. Deadlock Detection and Recovery | 死锁检测与恢复
When prevention and avoidance are not used, the system can allow deadlocks to occur, detect them, and then take recovery action. Detection typically involves constructing a resource-allocation graph or using a detection algorithm similar to the Banker’s algorithm but without prior knowledge of maximum needs.
如果不采用预防和避免策略,系统可以允许死锁发生,然后检测并采取恢复措施。检测通常涉及构建资源分配图,或者使用类似于银行家算法但没有最大需求先验知识的检测算法。
Once deadlock is detected, recovery can be performed by aborting one or more processes (process termination) or by preempting resources from some processes and giving them to others. The chosen victim should minimise cost, but care must be taken to avoid starvation – where a process is perpetually denied necessary resources.
一旦检测到死锁,可以通过中止一个或多个进程(进程终止)或从某些进程中抢占资源并分配给其他进程来进行恢复。所选择的牺牲进程应该使成本最小化,但必须小心避免饥饿——即某个进程永远得不到所需资源的情况。
10. Livelock and Other Conflict Patterns | 活锁与其他冲突模式
Livelock is a subtle conflict state similar to deadlock, but instead of being blocked, processes keep changing state in response to each other without making any real progress. Imagine two people trying to pass each other in a corridor and repeatedly stepping to the same side – they are active but stuck in a loop.
活锁是一种类似于死锁的微妙冲突状态,但进程并没有被阻塞,而是不断地相互响应而改变状态,却没有取得任何实际进展。想象两个人试图在走廊里互相让路,却反复迈向了同一侧——他们虽然活动着,但陷入了一个循环。
Starvation occurs when a process is ready to run but is indefinitely postponed because other processes are always given priority, or when a thread cannot acquire a lock because faster threads keep snatching it. Fair scheduling and lock acquisition policies are needed to avoid such indefinite waiting.
饥饿发生在进程已就绪但被无限期推迟的情况,原因是其他进程总是被赋予更高优先级,或者线程无法获得锁因为更快的线程不断地抢走锁。需要公平的调度和锁获取策略来避免这种无限等待。
11. Conflict in Distributed and Networked Environments | 分布式与网络环境中的冲突
In distributed systems, conflicts become more complex due to message delays, partial failures, and the absence of a global clock. For instance, two nodes might attempt to update the same replica of a database simultaneously, creating a replica conflict. Solutions include distributed mutual exclusion algorithms, timestamp-based ordering, and consensus protocols like Paxos.
在分布式系统中,由于消息延迟、部分故障和缺乏全局时钟,冲突变得更加复杂。例如,两个节点可能试图同时更新数据库的同一副本,造成副本冲突。解决方案包括分布式互斥算法、基于时间戳的排序以及像 Paxos 这样的共识协议。
In computer networks, the classic conflict occurs in the shared medium of early Ethernet: if two stations transmit at the same time, a collision happens. Carrier Sense Multiple Access with Collision Detection (CSMA/CD) detects these collisions and initiates a random backoff algorithm to resolve the conflict, allowing orderly retransmission.
在计算机网络中,经典的冲突发生在早期以太网的共享介质上:如果两个站点同时传输,就会发生碰撞。带有碰撞检测的载波侦听多路访问(CSMA/CD)检测到这些碰撞并启动随机退避算法来解决冲突,使得能够有序地重传。
12. Key Takeaways and Practical Relevance | 要点总结与实际意义
Conflict in computing arises from the fundamental need to share resources safely among concurrent activities. The study of race conditions, mutual exclusion, deadlock and associated algorithms is not only a key part of the A-Level Computer Science curriculum but also an essential skill for software engineers writing multi-threaded code, database designers, and system architects.
计算中的冲突源于在并发活动中安全共享资源的根本需求。对竞态条件、互斥、死锁和相关算法的研究,不仅是 A-Level 计算机科学课程的关键组成部分,也是编写多线程代码的软件工程师、数据库设计者和系统架构师的必备技能。
Understanding how to use synchronisation primitives like semaphores and mutexes, design deadlock-free resource allocation policies, and apply detection and recovery strategies provides a foundation for building reliable, high-performance systems in an increasingly parallel and distributed computing world.
理解如何使用信号量和互斥量等同步原语,设计无死锁的资源分配策略,并应用检测与恢复策略,为在一个日益并行和分布式的计算世界中构建可靠、高性能的系统奠定了基础。
Published by TutorHao | Computer Science Revision Series | aleveler.com
更多咨询请联系16621398022(同微信)
屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导