Back to series
· 14 min read

Concurrency and Parallelism: How Is Multitasking Actually Implemented?


1. Why do computers need to handle multiple tasks at the same time?

Modern computers usually need to handle a large number of tasks at the same time.

For example, when we use a computer, we may be:

  • Browsing web pages.
  • Playing music.
  • Downloading files.
  • Editing code.
  • Running a database.
  • Executing background programs.

These tasks appear to run at the same moment, but the way the computer executes them internally is not entirely the same.

Some tasks are executed alternately through rapid CPU switching, while others are truly executed simultaneously by multiple CPU cores.

This leads to two important concepts:

  • Concurrency: multiple tasks make progress alternately over a period of time, appearing as simultaneous execution at a macro level.
  • Parallelism: multiple tasks are truly executed at the same moment, requiring the corresponding hardware execution capability.

Understanding the difference between the two is the foundation for understanding operating systems, thread pools, asynchronous programming, distributed systems, and high-performance computing.

1.1 From Single Task to Multitasking

Suppose a program needs to complete three tasks:

  • A: Read a file.
  • B: Compute data.
  • C: Send a network request.

The simplest way is sequential execution:

flowchart TD
    A["Start"] --> B["Execute Task A"]
    B --> C["Execute Task B"]
    C --> D["Execute Task C"]
    D --> E["End"]
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style C fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style D fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style E fill:#F1F5F9,stroke:#CBD5E1,color:#475569

If task A needs to wait for disk reading to complete, the CPU may not be able to continue with subsequent computation during the wait.

A more reasonable approach is:

  • While task A is waiting for the disk, execute task B.
  • While task B is waiting for other resources, execute task C.
  • After a task completes, continue processing other tasks.

This can reduce CPU idle time and improve overall system efficiency.

1.2 Core Objectives of Multitasking

Goal Meaning
Improve CPU utilization Minimize processor idle time
Improve throughput Complete more tasks per unit time
Reduce response latency Let tasks be processed as soon as possible
Improve resource utilization Make full use of CPU, memory, disk, and network
Improve system scalability Support more tasks running simultaneously
Improve user experience Prevent one task from blocking the entire application

Although concurrency and parallelism can both help a system handle multiple tasks, they solve problems in different ways.

2. What Is Concurrency?

Concurrency means that multiple tasks all make execution progress within the same time period.

The key is: the execution times of multiple tasks overlap, but they are not required to execute at the same physical instant.

2.1 How Does a Single-Core CPU Achieve Concurrency?

Suppose the computer has only one CPU core and needs to run three tasks:

  • T1: Browser task.
  • T2: Music player task.
  • T3: Background computing task.

Since a single CPU core can execute only one ordinary execution flow at a given moment, the operating system uses task switching to let them execute alternately.

For example:

Timeline:

0ms    5ms   10ms   15ms   20ms   25ms
| T1   | T2  | T3   | T1   | T2   | T3   |

The CPU does not actually execute three tasks at the same time; instead, it switches rapidly between different tasks.

This method is concurrency.

2.2 The Execution Process of Concurrency

flowchart TD
    A["Multiple tasks enter the system"] --> B["Operating system scheduler"]
    B --> C["Select task T1"]
    C --> D["CPU executes T1"]
    D --> E{"Whether a switch is needed"}
    E -->|"Yes"| F["Save T1 context"]
    F --> G["Select task T2"]
    G --> H["CPU executes T2"]
    H --> I{"Whether to continue switching"}
    I -->|"Yes"| J["Save T2 context"]
    J --> K["Select another task"]
    K --> D
    I -->|"No"| H
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style E fill:#F3EAF7,stroke:#BFA8CE,color:#59466B
    style F fill:#F1F5F9,stroke:#CBD5E1,color:#475569
    style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style H fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style I fill:#F3EAF7,stroke:#BFA8CE,color:#59466B
    style J fill:#F1F5F9,stroke:#CBD5E1,color:#475569
    style K fill:#E8E2F8,stroke:#B5A4DC,color:#514276

Concurrency usually relies on the following mechanisms:

  1. The operating system maintains multiple runnable tasks.
  2. The scheduler selects the task currently to execute.
  3. It obtains scheduling opportunities through mechanisms such as timer interrupts.
  4. Save the execution context of the current task.
  5. Restore the execution context of other tasks.
  6. Repeat the above process continuously.

2.3 Time Slices and Concurrency

Operating systems usually control how long tasks occupy the CPU through scheduling mechanisms.

For example, the time-slice round-robin model:

CPU core:

T1: runs for 10ms
T2: runs for 10ms
T3: runs for 10ms
T1: runs again for 10ms
T2: runs again for 10ms

Tasks alternate execution on the CPU, thereby creating a concurrency effect.

However, not all operating systems use a fixed time-slice round-robin algorithm. Modern operating systems select tasks according to different scheduling policies, and the specific time allocation mechanisms also vary.

2.4 Concurrency Does Not Necessarily Mean Multiple Threads

Concurrency is a way of organizing and executing tasks; it does not mean that multiple threads must be created.

For example:

  • One thread uses an event loop to handle multiple network connections.
  • One thread waits for multiple file operations through asynchronous I/O.
  • One process alternates between multiple tasks through coroutines.

All of these can achieve concurrency.

Therefore, it is necessary to distinguish:

  • Concurrency: Multiple tasks make progress together over a period of time.
  • Multithreading: A technique for organizing multiple execution flows.
  • Multiprocessing: A technique for organizing tasks through multiple processes.
  • Asynchrony: A programming approach that prevents waiting operations from blocking the execution flow.

3. What Is Parallelism?

Parallelism means that multiple tasks are truly executing at the same time within the same physical time period.

It usually requires multiple independent execution units.

For example:

  • Two CPU cores execute different threads respectively.
  • A large number of compute units in a GPU process data simultaneously.
  • Multiple servers process different requests simultaneously.

3.1 How Do Multi-Core CPUs Achieve Parallelism?

Suppose a CPU has four cores:

CPU Core 0: execute task T1
CPU Core 1: execute task T2
CPU Core 2: execute task T3
CPU Core 3: execute task T4

The four tasks can execute at the same instant.

This is true parallelism.

3.2 The Parallel Execution Process

flowchart TD
    A["Multiple independent tasks"] --> B["Task dispatcher"]
    B --> C["CPU Core 0"]
    B --> D["CPU Core 1"]
    B --> E["CPU Core 2"]
    B --> F["CPU Core 3"]
    C --> G["Execute task T1"]
    D --> H["Execute task T2"]
    E --> I["Execute task T3"]
    F --> J["Execute task T4"]
    G --> K["Aggregate results"]
    H --> K
    I --> K
    J --> K
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style G fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style H fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style I fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style J fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style K fill:#E0F0FE,stroke:#93BCE8,color:#1E4976

The core condition for parallel execution is that the system has multiple execution units that can work at the same time, and tasks can be reasonably split.

3.3 Common Hardware Foundations for Parallelism

Multi-core CPU

A processor chip contains multiple CPU cores, and each core can independently execute an instruction stream.

Multi-socket CPUs

A server is equipped with multiple physical processors, and each processor may itself contain multiple cores.

Hyper-Threading and SMT

A physical core can expose multiple logical CPUs, allowing the processor to schedule another hardware thread when some execution resources are idle.

Note that SMT provides resource sharing at the hardware-thread level; it does not amount to adding the same number of full physical cores.

GPU

A GPU has a large number of compute units and is suited to executing many independent, structurally similar computational tasks.

Distributed computing nodes

Multiple servers collaborate over a network to process tasks, achieving parallelism across machines.

IV. What Is the Difference Between Concurrency and Parallelism?

Concurrency and parallelism often appear together, but they are not the same concept.

4.1 Key Differences

Comparison Dimension Concurrency Parallelism
Core meaning Multiple tasks make progress alternately Multiple tasks execute simultaneously
Requires multiple cores? Not required Usually requires multiple execution units
Supported on a single-core CPU? Supported Does not support true multi-task parallelism
Main goal Improve task progress capability Improve computational throughput
Typical mechanisms Time slicing, event loops, coroutines Multi-core, multiprocessor, GPU
Main challenges Task scheduling, state management Task splitting, load balancing
Typical scenarios Network services, I/O waiting Image processing, scientific computing

4.2 Timeline Comparison

Concurrency:

Single-core CPU:

Time →
| T1 | T2 | T1 | T3 | T2 | T1 |

Parallelism:

Multi-core CPU:

Time →
Core 0: | T1 | T1 | T1 | T1 |
Core 1: | T2 | T2 | T2 | T2 |
Core 2: | T3 | T3 | T3 | T3 |

4.3 Relationship Between Concurrency and Parallelism

Concurrency is a way of organizing tasks; parallelism is the ability for tasks to actually execute at the same time.

The two can be used in combination:

  • Single-core CPU: It can be concurrent, but it cannot truly execute multiple threads in parallel at the same instant.
  • Multi-core CPU: It can be both concurrent and parallel.
  • Multiple tasks on a multi-core CPU: They may be executed in parallel, or they may execute alternately due to scheduling.
  • Single-threaded event loop: It can handle multiple tasks concurrently, but it usually does not execute the code of multiple tasks simultaneously within one thread.

The two can be understood as:

flowchart TD
    A["Multitasking"] --> B["Concurrency"]
    A --> C["Parallelism"]
    B --> D["Tasks take turns making progress"]
    B --> E["Event loop and coroutines"]
    B --> F["Multithreading and multiprocessing"]
    C --> G["Multicore CPU"]
    C --> H["GPU"]
    C --> I["Distributed computing"]
    F --> J["Can also use multiple cores for parallelism"]
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style C fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style D fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style E fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style F fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style H fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style I fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style J fill:#E8E2F8,stroke:#B5A4DC,color:#514276

V. How Does the Operating System Implement Concurrency?

Concurrency is not just the CPU rapidly switching between tasks; it also requires the operating system to maintain task state, execution contexts, and scheduling information.

5.1 Processes: Resource-Isolated Runtime Environments

A process is one running instance of a program.

The operating system uses processes to manage the execution environments of multiple independent programs.

A process typically has:

  • An independent virtual address space.
  • Code and data segments.
  • Heap and memory-mapped regions.
  • File descriptors.
  • One or more threads.

Different processes usually have mutually isolated address spaces.

For example:

Process A
├── Code segment
├── Data segment
├── Heap
└── Threads

Process B
├── Code segment
├── Data segment
├── Heap
└── Threads

Processes can communicate through IPC mechanisms provided by the operating system.

5.2 Threads: Independent Execution Flows

A thread is one of the basic units of operating system scheduling and execution.

Multiple threads in the same process share:

  • Code segment.
  • Global data.
  • Heap memory.
  • File descriptors.
  • Process address space.

But each thread has its own:

  • Program counter.
  • CPU register state.
  • Thread stack.
  • Thread-local storage.
  • Scheduling state.

For example:

Process Browser
│
├── UI Thread
│   └── Handle user input
│
├── Network Thread
│   └── Handle network requests
│
├── Render Thread
│   └── Render pages
│
└── Worker Thread
    └── Background computation

These threads can run alternately, and can also truly run in parallel on a multicore CPU.

5.3 Context Switching

A context switch is an important mechanism by which the operating system implements multitasking concurrency.

When the CPU switches from thread A to thread B, it needs to save A's execution state and restore B's execution state.

Typical process:

flowchart TD
    A["Thread A is executing"] --> B["A scheduling event occurs"]
    B --> C["Enter the kernel"]
    C --> D["Save thread A context"]
    D --> E["Update thread A state"]
    E --> F["Scheduler selects thread B"]
    F --> G["Restore thread B context"]
    G --> H["Thread B starts executing"]
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style C fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style E fill:#F1F5F9,stroke:#CBD5E1,color:#475569
    style F fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976

Context switching involves:

  • Saving registers.
  • Saving the program counter.
  • Saving the stack pointer.
  • Restoring the target thread's state.
  • Updating scheduling-related data.

The context switch itself consumes CPU time and may also affect cache locality.

Therefore, more threads is not necessarily better.

5.4 Timer Interrupts and Task Switching

The operating system needs some mechanism to obtain scheduling opportunities.

In many systems, the timer interrupt is one of the important sources of scheduling triggers.

For example:

  1. The CPU is executing thread A.
  2. The timer generates an interrupt.
  3. The CPU enters the kernel interrupt handling flow.
  4. The kernel updates time and scheduling-related state.
  5. If rescheduling is needed, select another runnable task.
  6. Resume the target task at the appropriate time.

Note that a timer interrupt does not mean a thread switch necessarily occurs on every interrupt. The operating system also decides whether to switch based on task state, scheduling policy, and preemption conditions.

VI. How does multithreading achieve concurrency and parallelism?

Multithreading is one of the most common techniques for achieving concurrency and parallelism.

6.1 Multithreaded Concurrency

Suppose there are three threads:

  • T1: Read a file.
  • T2: Process data.
  • T3: Send a network request.

On a single-core CPU, the three threads can achieve concurrency by executing alternately.

Single-core CPU:

Time →
| T1 | T2 | T3 | T1 | T2 | T3 |

6.2 Multithreaded Parallelism

On a quad-core CPU, four threads can be run on different cores respectively.

CPU Core 0: T1
CPU Core 1: T2
CPU Core 2: T3
CPU Core 3: T4

6.3 Multithreading Execution Model

flowchart TD
    A["Main thread creates worker threads"] --> B["Thread scheduling"]
    B --> C["Single-core environment"]
    B --> D["Multi-core environment"]
    C --> E["Multiple threads execute alternately"]
    D --> F["Multiple threads execute simultaneously"]
    E --> G["Concurrency"]
    F --> H["Parallelism"]
    G --> I["Shared task state"]
    H --> I
    I --> J["Thread synchronization and result aggregation"]
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style E fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style F fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style G fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style H fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style I fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style J fill:#F1F5F9,stroke:#CBD5E1,color:#475569

It should be emphasized:

Multithreading is not the same as multi-core parallelism.

Threads provide multiple execution flows; whether they actually run in parallel depends on hardware resources, operating system scheduling, and the program's runtime environment.

VII. Why are I/O-intensive tasks particularly suitable for concurrency?

Concurrency is very important in scenarios such as network services, databases, and file processing.

The reason is that these tasks often need to wait for external resources.

7.1 I/O Waiting Causes CPU Idle Time

For example, a network program needs to perform the following:

  1. Send an HTTP request.
  2. Wait for the server response.
  3. Read the response content.
  4. Parse the data.

Among these, the time spent waiting for the server response may be far greater than the actual CPU computation time.

If a synchronous blocking approach is used, a thread cannot continue executing other code while waiting.

7.2 Multithreaded I/O Processing

Different threads can be assigned to different requests.

When one thread is waiting for a network response, other threads can continue working.

flowchart TD
    A["Multiple network requests"] --> B["Thread pool"]
    B --> C["Thread 1"]
    B --> D["Thread 2"]
    B --> E["Thread 3"]
    C --> F["Waiting for response to request A"]
    D --> G["Processing request B"]
    E --> H["Processing request C"]
    F --> I["Request A data arrives"]
    I --> J["Continue processing request A"]
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style F fill:#F1F5F9,stroke:#CBD5E1,color:#475569
    style G fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style H fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style J fill:#DCEFE5,stroke:#8EBFA5,color:#24563F

7.3 Asynchronous I/O and the Event Loop

In addition to multithreading, asynchronous I/O can also be used.

An asynchronous program does not need to allocate a thread for every request that is waiting.

It can manage multiple tasks through an event loop.

For example:

  • Initiate a network request.
  • Register a wait event.
  • Continue executing other tasks.
  • Receive a notification when data arrives.
  • Resume the corresponding task to continue execution.
flowchart TD
    A["Submit multiple I/O tasks"] --> B["Event loop"]
    B --> C["Initiate asynchronous I/O"]
    C --> D["Register wait event"]
    D --> E["Continue processing other tasks"]
    E --> F["I/O completion notification"]
    F --> G["Event loop retrieves completion events"]
    G --> H["Resume corresponding task"]
    H --> I["Process result"]
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#F1F5F9,stroke:#CBD5E1,color:#475569
    style E fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style G fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style H fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style I fill:#FFF2CC,stroke:#E4C66A,color:#725719

Asynchronous I/O is suitable for a large number of wait-heavy tasks, such as:

  • Web servers.
  • Network proxies.
  • Message middleware.
  • High-concurrency API services.
  • Long-connection services.

However, asynchronous I/O does not mean that CPU computation will also automatically run in parallel. Computational code in a single-threaded event loop is usually still executed sequentially.

8. How Can CPU-Intensive Tasks Achieve Parallelism?

Unlike I/O-intensive tasks, CPU-intensive tasks mainly consume processor computing resources.

For example:

  • Image processing.
  • Video encoding.
  • Large-scale matrix operations.
  • Scientific computing.
  • Data compression.
  • Model inference.

These tasks are usually better suited to achieving parallelism using multi-core CPUs or GPUs.

8.1 Split a Large Task into Multiple Subtasks

Suppose you need to process an image containing 10 million pixels.

If processed by a single thread:

Thread 1:
Process pixels 0 to 10 million

If four threads are used:

Thread 1: Process pixels 0 to 2.5 million
Thread 2: Process pixels 2.5 million to 5 million
Thread 3: Process pixels 5 million to 7.5 million
Thread 4: Process pixels 7.5 million to 10 million

Each thread processes an independent data region.

8.2 Data Parallelism

Data Parallelism is the practice of dividing data into multiple parts and having different computing units perform the same or similar operations.

flowchart TD
    A["Input Data"] --> B["Data Partitioning"]
    B --> C["Data Block 1"]
    B --> D["Data Block 2"]
    B --> E["Data Block 3"]
    B --> F["Data Block 4"]
    C --> G["CPU Core 0"]
    D --> H["CPU Core 1"]
    E --> I["CPU Core 2"]
    F --> J["CPU Core 3"]
    G --> K["Result Merge"]
    H --> K
    I --> K
    J --> K
    K --> L["Output Result"]
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style G fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style H fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style I fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style J fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style K fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976

8.3 Task Parallelism

Task Parallelism means having different execution units handle different types of tasks.

For example, a video processing system:

  • Thread A: Decode video.
  • Thread B: Process images.
  • Thread C: Encode video.
  • Thread D: Write to file.

These tasks can form a pipeline and advance simultaneously when data dependency conditions are met.

8.4 Differences Between Data Parallelism and Task Parallelism

Comparison Dimension Data Parallelism Task Parallelism
Core Idea The same operation processes different data Different tasks execute simultaneously
Computation Logic Usually the same or similar Can be completely different
Typical Scenarios Matrix computation, image processing Video pipelines, service processing
Main Challenges Data partitioning and result merging Task dependencies and resource coordination

IX. Synchronization Issues in Concurrency and Parallelism

When multiple tasks access shared resources at the same time, data races may occur.

This is also one of the most important issues in concurrent programming.

9.1 Race Conditions

A race condition means that the program's execution result is affected by the execution order or timing of multiple tasks.

For example:

counter = 0

def increment():
    global counter
    counter += 1

Suppose two threads execute increment() at the same time.

We expect the final result to be:

counter = 2

However, without synchronization protection, the two threads may execute in the following order:

Thread A: Read counter = 0
Thread B: Read counter = 0
Thread A: Compute 0 + 1
Thread B: Compute 0 + 1
Thread A: Write counter = 1
Thread B: Write counter = 1

The final result may be 1 instead of 2.

This is a race condition.

9.2 Critical Section

A critical section is a region of code that accesses shared resources.

For example:

counter += 1

If this operation is not atomic and multiple threads access it at the same time, a race condition may occur.

The critical section needs to be protected by a synchronization mechanism.

9.3 Mutex Lock

A mutex is a common synchronization mechanism.

It ensures that only one thread can enter the protected critical section at any given time.

Python example:

import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter

    with lock:
        counter += 1

threads = []

for _ in range(10):
    t = threading.Thread(target=increment)
    threads.append(t)
    t.start()

for t in threads:
    t.join()

print(counter)

Protecting a shared variable with a mutex prevents multiple threads from modifying it at the same time.

9.4 Semaphore

A semaphore allows a certain number of threads to access a resource at the same time.

For example:

A database connection pool allows at most 5 concurrent connections.

import threading
import time

semaphore = threading.Semaphore(5)

def worker():
    with semaphore:
        print("开始执行")
        time.sleep(1)
        print("执行完成")

Compared with a mutex:

  • A mutex is mainly used for mutually exclusive access.
  • A semaphore is mainly used to limit the number of concurrent tasks or to coordinate tasks.

9.5 Condition Variable

A condition variable is used for waiting and notification between threads.

The typical scenario is the producer–consumer model.

  • The producer is responsible for generating data.
  • The consumer is responsible for processing data.
  • The consumer waits when there is no data.
  • The producer notifies the consumer after producing data.
flowchart TD
    A["Producer generates data"] --> B["Write to shared queue"]
    B --> C["Notify consumer"]
    C --> D["Consumer is woken up"]
    D --> E["Read data from queue"]
    E --> F["Process data"]
    G["Consumer finds the queue empty"] --> H["Wait for condition to be met"]
    H --> C
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style C fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style D fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style F fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style G fill:#F1F5F9,stroke:#CBD5E1,color:#475569
    style H fill:#E8E2F8,stroke:#B5A4DC,color:#514276

9.6 Atomic Operation

An atomic operation is an operation whose intermediate state cannot be observed by other threads.

For example:

  • Atomic addition.
  • Atomic swap.
  • Atomic compare-and-swap (CAS).

The basic idea of CAS:

Compare the current value with the expected value
                        |
                        v
                  Are they equal?
                   /          \
                 yes           no
                  |             |
            update value       fails
                  |
          operation succeeded

Atomic operations can be used to build lock-free data structures, but lock-free does not mean there are no synchronization issues; you also need to consider memory visibility, memory ordering, the ABA problem, and so on.

9.7 Comparison of Concurrency Safety Mechanisms

Mechanism Main purpose Typical scenario
Mutex Mutually exclusive access Protecting shared variables
Semaphore Limiting concurrency Connection pool
Condition Variable Waiting and notification Producer–consumer
Atomic Atomic update Counters, status flags
Read-Write Lock Separating reads from writes Read-heavy, write-light
Barrier Synchronizing multiple tasks to the same stage Parallel computing

10. Deadlock Problems in Concurrent Programming

Deadlock means that multiple tasks are each waiting for a resource held by another, so that none of the tasks involved can continue executing.

10.1 Deadlock Example

Suppose there are two threads and two locks:

  • Thread A holds lock L1 and waits for lock L2.
  • Thread B holds lock L2 and waits for lock L1.
flowchart TD
    A["Thread A holds L1"] --> B["Waiting for L2"]
    C["Thread B holds L2"] --> D["Waiting for L1"]
    B --> E["L2 is held by Thread B"]
    D --> F["L1 is held by Thread A"]
    E --> C
    F --> A
    style A fill:#FCE8E6,stroke:#E2A5A0,color:#783F3B
    style B fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style C fill:#FCE8E6,stroke:#E2A5A0,color:#783F3B
    style D fill:#FFF2CC,stroke:#E4C66A,color:#725719
    style E fill:#E8E2F8,stroke:#B5A4DC,color:#514276
    style F fill:#E8E2F8,stroke:#B5A4DC,color:#514276

10.2 The Four Necessary Conditions for Deadlock