I. Why Do Computers Need Processes and Threads?
A computer usually needs to run multiple programs at the same time.
For example:
- A browser is opening multiple web pages.
- A music player is playing music.
- An editor is working on code.
- A download tool is downloading files.
- A background service is handling network requests.
These programs appear to be running simultaneously, but the number of CPU cores is limited, so it is impossible for every task to monopolize a processor at the same moment.
The operating system needs to solve several problems:
- How to manage multiple running programs?
- How to allocate CPU time?
- How to isolate the memory and resources of different programs?
- How to let multiple tasks inside a single program execute concurrently?
- How to let different tasks share data safely?
To solve these problems, the operating system introduced two important concepts: processes and threads.
Processes are responsible for providing resource management and isolated environments; threads are responsible for executing the actual program instructions.
We can start with an intuitive picture:
Computer
│
├── Process A
│ ├── Thread A1
│ ├── Thread A2
│ └── Thread A3
│
├── Process B
│ ├── Thread B1
│ └── Thread B2
│
└── Process C
└── Thread C1
A process can contain one or more threads.
Multiple threads can work together within the same process, while multiple processes usually have mutually independent virtual address spaces.
II. What Is a Process?
1. Definition of a Process
A process is an instance of a program in execution, and an important unit for the operating system to allocate, manage, and isolate resources.
For example, there is a browser executable file on disk:
/usr/bin/browser
When the user launches the browser, the operating system creates the corresponding process.
If the user launches another independent browser instance, the system can create yet another process.
Therefore:
- A program is static instructions and data.
- A process is a dynamic entity formed when a program runs.
- One program can correspond to multiple processes.
- A process has its own running state and resource management information.
A process is not simply an executable file; it is a whole environment established by the operating system for a program to run.
2. What Does a Process Contain?
A process usually contains the following components:
| Component | Main Purpose |
|---|---|
| Code segment | Stores the program's machine instructions |
| Data segment | Stores global variables and static variables |
| Heap | Manages dynamically allocated memory |
| Stack | Stores function call information and local variables |
| Virtual address space | Provides an independent memory view for the process |
| File descriptors | Manage open files and I/O objects |
| Process control information | Stores information such as PID, state, and permissions |
| Thread execution contexts | Stores each thread's registers and running state |
A process may contain multiple threads, so a process holds not only resource management information but must also manage the execution state of its internal threads.
3. Core Characteristics of a Process
Independence
Each process usually has its own independent virtual address space. A process cannot arbitrarily access the private memory of another process.
Dynamism
A process has lifecycle states such as creation, running, blocking, resuming, and termination.
Concurrency
Multiple processes can take turns using the CPU, and can also run truly in parallel on multicore processors.
Resource ownership
A process is an important boundary for resource management and can own resources such as memory mappings, file descriptors, and signal handling settings.
Isolation
Through address space isolation, permission checks, and resource control, the operating system limits direct interference between processes.
4. The Lifecycle of a Process
From creation to exit, a process goes through multiple states.
The classic process state model includes:
| State | Meaning |
|---|---|
| New | The process is being created |
| Ready | Has met the conditions to run and is waiting for the CPU |
| Running | Executing on the CPU |
| Blocked | Waiting for some event or resource |
| Terminated | The process has finished |
Typical state transitions are as follows:
flowchart TD
A["New"] --> B["Ready"]
B --> C["Running"]
C --> D["Terminated"]
C --> E["Blocked"]
E --> B
C --> B
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#FFF1D6,stroke:#E7C77E,color:#76551E
style D fill:#F1F3F5,stroke:#CBD5E1,color:#334155
style E fill:#E6DFF5,stroke:#B6A4D8,color:#51416F
For example, a process is reading a file from disk:
- The process gets the CPU and starts executing.
- It issues a file read request.
- Because it must wait for I/O, it enters the blocked state.
- The disk operation completes.
- The process re-enters the ready state.
- The scheduler allocates the CPU again.
- The process continues executing.
Note that modern Linux kernels use a more fine-grained task state model; the classic five-state model is mainly used to understand the process lifecycle.
5. How does the operating system manage processes?
The operating system needs to record each process's identity, state, resources, and execution information.
In traditional operating system theory, PCB — Process Control Block — is commonly used to describe this information.
In the Linux kernel, process- and thread-related task information is mainly managed by the task_struct structure.
The information it contains covers:
- Process and thread identifiers.
- Scheduling state.
- CPU scheduling information.
- Memory management information.
- File descriptor information.
- Signal handling information.
- Parent-child task relationships.
- Permissions and resource limits.
You can view processes with the following Linux command:
ps -ef
View a specific process:
ps -p 1234 -o pid,ppid,stat,comm
View the PID of the current shell:
echo $$
In C, you can use:
#include <stdio.h>
#include <unistd.h>
int main(void) {
printf("PID: %d\n", getpid());
printf("PPID: %d\n", getppid());
return 0;
}
Where:
getpid()gets the PID of the current process.getppid()gets the PID of the current process's parent process.
III. What Is a Thread?
1. Definition of a thread
A thread is a task entity inside a process that can be scheduled and executed independently.
It is an important unit of CPU scheduling.
A process can contain one thread or multiple threads.
For example, a browser process might contain:
- A user interface thread.
- A network request thread.
- A rendering thread.
- A timer task thread.
- A background worker thread.
These threads can share the resources of the process they belong to while each executing different tasks.
2. Why are threads needed?
Suppose a program has only one execution thread and must complete three tasks at the same time:
- Read a file.
- Process data.
- Update the interface.
If all the work is done sequentially by the same thread, then while reading a file it may have to wait for disk I/O, and the interface cannot be updated in time.
With multithreading, different tasks can be assigned to different threads.
For example:
Application process
│
├── Main thread
│ └── Update UI
│
├── Worker thread A
│ └── Read file
│
└── Worker thread B
└── Process data
While a worker thread waits for the file read, the main thread can still handle interface events.
This improves the program's responsiveness and resource utilization.
3. What are the components of a thread?
One of the biggest differences between threads and processes is how resources are shared.
Threads in the same process usually share process-level resources, but each thread has its own execution context.
| Thread-private content | Purpose |
|---|---|
| Thread ID | Identifies the thread |
| Program counter | Records the position of the next instruction to execute |
| CPU registers | Save the thread's current execution state |
| Thread stack | Stores function calls and local variables |
| Scheduling state | Indicates whether the thread is runnable or waiting |
| Thread-local storage | Stores data private to the thread |
Threads usually share the following from the process they belong to:
- Code segment.
- Global variables.
- Static variables.
- Heap memory.
- File descriptors.
- Address space.
- Process-level resources.
This relationship can be understood as:
Process shared resources
┌─────────────────────────────────────────────┐
│ Code segment │
│ Global variables │
│ Heap memory │
│ File descriptors │
│ Virtual address space │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Thread A │ │ Thread B │ │
│ │ Registers │ │ Registers │ │
│ │ Program counter │ │ Program counter │ │
│ │ Thread stack │ │ Thread stack │ │
│ └─────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────┘
Sharing data between threads is more convenient, but it also means concurrent access issues must be handled.
4. What Is a Thread Stack?
Each thread needs its own stack.
Suppose a process has two threads:
void task_a(void) {
int value = 100;
}
void task_b(void) {
int value = 200;
}
When the two threads execute these functions respectively, each has its own independent function call stack.
Even if the local variables have the same name, they usually occupy different locations in stack memory.
Therefore, when Thread A modifies its own local variable, it does not directly modify Thread B's local variable with the same name.
However, if a local variable holds a pointer to shared heap memory, the two threads may still access the same block of data.
5. Thread Lifecycle
Threads also typically have states such as created, ready, running, blocked, and terminated.
A typical process:
flowchart TD
A["Create thread"] --> B["Ready"]
B --> C["Running"]
C --> D["Thread exits"]
C --> E["Blocked or waiting"]
E --> B
C --> B
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#FFF1D6,stroke:#E7C77E,color:#76551E
style D fill:#F1F3F5,stroke:#CBD5E1,color:#334155
style E fill:#E6DFF5,stroke:#B6A4D8,color:#51416F
Thread states are managed jointly by the operating system and the thread runtime environment.
In Linux, threads also participate in kernel scheduling as schedulable tasks.
IV. What Is the Difference Between a Process and a Thread?
Processes and threads are closely related, but they are not the same concept.
The most important difference is:
Processes are primarily responsible for resource management and isolation, while threads are primarily responsible for executing tasks.
1. Comparison of Core Differences
| Comparison dimension | Process | Thread |
|---|---|---|
| Basic concept | A running program instance | Execution entity within a process |
| Primary responsibility | Resource management and isolation | Instruction execution and task scheduling |
| Address space | Usually independent | Shared by threads in the same process |
| Code segment | Owned by the process | Shares the code of its process |
| Global variables | Owned independently by the process | Shared by threads in the same process |
| Heap memory | Managed independently by the process | Shared by threads in the same process |
| Stack | Each thread has its own stack | Each thread has its own stack |
| Register state | Saved separately by the threads in the process | Saved independently by each thread |
| Creation cost | Usually higher | Usually lower |
| Switching cost | Usually higher | Switching between threads in the same process is usually lower |
| Communication method | Often requires IPC mechanisms | Can directly access shared data |
| Failure impact | Usually confined to the process and related resources | One thread can cause the entire process to fail |
| Isolation capability | Relatively strong | Relatively weak |
The cost comparisons here are general rules, not absolute conclusions that hold under all operating systems and scenarios.
2. Different Memory Spaces
Processes usually have independent virtual address spaces.
For example:
Process A
Virtual address 0x1000
│
▼
Physical memory region A
Process B
Virtual address 0x1000
│
▼
Physical memory region B
Two processes can use the same virtual address but map it to different physical memory pages.
Therefore, one process usually cannot directly modify another process's private variables.
Threads in the same process, however, share the same virtual address space:
Process A
│
├── Thread A1
├── Thread A2
└── Thread A3
The three threads share:
├── Code segment
├── Data segment
├── Heap memory
└── Address space
Threads can directly access shared data within the process.
3. Different Ways of Sharing Resources
Processes are isolated by default and need to exchange data through explicit communication mechanisms.
Threads, by contrast, can directly access shared memory within the same process.
For example:
int shared_value = 0;
Multiple threads in the same process can access shared_value.
However, even if multiple processes use the same variable name, they do not automatically access the same variable instance.
If you want processes to share data, you need to use:
- Shared memory.
- Message queues.
- Pipes.
- Unix Domain Socket.
- Network Socket.
- Other IPC mechanisms.
4. Different Creation and Switching Costs
Creating a process usually requires setting up independent process management information and an address space.
Creating a thread can usually reuse the existing address space and resources of its process.
Therefore, in many scenarios, creating a thread costs less than creating a separate process.
Context switching shows a similar difference:
- Switching between threads within the same process usually does not require switching to another process's address space.
- Switching between different processes usually involves handling address-space-related state.
- The actual switching cost also depends on the CPU architecture, caches, kernel implementation, and scheduling scenario.
You cannot simply assume that thread switching is always fast and process switching is always slow.
5. Different Scope of Failure Impact
A process has a relatively independent address space.
When one process performs an illegal memory access, it usually does not directly corrupt the private memory of another ordinary process.
But threads within the same process share a large number of resources.
If a thread:
- modifies the wrong shared data,
- corrupts heap memory,
- causes an unhandled fatal signal,
- triggers a process-level crash,
it may affect the entire process.
So although multithreading improves concurrency, it also increases the complexity of managing shared state.
V. How Do Processes and Threads Cooperate in an Operating System?
To understand processes and threads, you cannot look only at the concepts; you also need to understand how the operating system creates, schedules, and manages them.
1. Process Creation
Taking Linux as an example, common ways of creating a process include:
fork()
fork() creates a child process.
The parent and child processes have different process identifiers and usually have independent views of the virtual address space.
Modern Linux generally uses copy-on-write to reduce the memory-copying cost at creation time.
A typical process:
flowchart TD
A["Parent process running"] --> B["Calls fork"]
B --> C["Kernel creates child process"]
C --> D["Set up child process management info"]
D --> E["Establish address space relationship"]
E --> F["Copy-on-write management"]
F --> G["Parent and child run separately"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#E6DFF5,stroke:#B6A4D8,color:#51416F
style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style F fill:#FFF1D6,stroke:#E7C77E,color:#76551E
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
2. Thread Creation
In Linux user programs, you can use the POSIX thread library to create threads.
For example:
pthread_create()
Example:
#include <stdio.h>
#include <pthread.h>
void *worker(void *arg) {
printf("工作线程正在运行\n");
return NULL;
}
int main(void) {
pthread_t tid;
if (pthread_create(&tid, NULL, worker, NULL) != 0) {
return 1;
}
pthread_join(tid, NULL);
printf("主线程结束\n");
return 0;
}
Compile:
gcc thread_demo.c -o thread_demo -pthread
Here:
pthread_create()creates a thread.worker()is the function the thread executes.pthread_join()waits for the specified thread to finish.pthread_tis used to represent a thread identifier.
3. How Does Linux Implement Threads?
In Linux, a thread is not a kernel object that exists entirely independently of a process.
The Linux kernel represents processes and threads uniformly as schedulable tasks.
When creating a thread, clone() or a related kernel mechanism is usually used so that the new task shares specified resources with the caller.
For example, threads within the same process typically share:
- the address space,
- the file descriptor table,
- file system related information,
- signal handling settings.
Each thread, however, maintains its own execution context and thread stack independently.
This is also why Linux often uses the term lightweight process to describe the thread implementation.
It is important to distinguish:
- POSIX threads are a thread interface standard aimed at applications.
pthread_create()is a user-space thread library interface.clone()is one of the low-level task creation mechanisms provided by Linux.
They sit at different levels of abstraction.
4. The Relationship Between Process and Thread Creation
flowchart TD
A["Application startup"] --> B["Create process"]
B --> C["Create process address space"]
C --> D["Create main thread"]
D --> E["Main thread runs"]
E --> F["Create worker thread"]
F --> G["Threads share process resources"]
G --> H["Multiple threads execute tasks"]
H --> I["Thread ends or waits"]
I --> J["Process continues running or exits"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style D fill:#E6DFF5,stroke:#B6A4D8,color:#51416F
style E fill:#FFF1D6,stroke:#E7C77E,color:#76551E
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#E6DFF5,stroke:#B6A4D8,color:#51416F
style I fill:#FFF1D6,stroke:#E7C77E,color:#76551E
style J fill:#F1F3F5,stroke:#CBD5E1,color:#334155
VI. What Are Concurrency and Parallelism?
Processes and threads often come up together with two concepts: concurrency and parallelism.
These two concepts are not the same.
1. What Is Concurrency?
Concurrency means that multiple tasks make progress alternately over a period of time.
Even with only one CPU core, the operating system can use task switching to give multiple tasks a chance to execute.
For example:
Single-core CPU
Time ─────────────────────>
Task A: Running Running Running
Task B: Running Running
Task C: Running
Overall, multiple tasks are all making progress, but at any given moment, the CPU core executes only one of them.
2. What Is Parallelism?
Parallelism means that multiple tasks actually execute at the same moment.
For example:
Multi-core CPU
CPU core 1: Task A ─────────
CPU core 2: Task B ─────────
CPU core 3: Task C ─────────
CPU core 4: Task D ─────────
Multiple cores can execute different tasks simultaneously.
3. Both Processes and Threads Can Achieve Concurrency and Parallelism
Whether using multiple processes or multiple threads, both can use the operating system's scheduling mechanisms to achieve concurrency.
If the system has multiple CPU cores and the tasks meet the conditions for parallel execution, true parallelism can also be achieved.
| Scenario | Can Be Concurrent | Can Be Parallel |
|---|---|---|
| Single-core multi-process | Yes | No |
| Single-core multi-thread | Yes | No |
| Multi-core multi-process | Yes | Yes |
| Multi-core multi-thread | Yes | Yes |
Note that the ability to run in parallel depends not only on the number of CPU cores, but also on whether there are dependencies between tasks and whether the program correctly uses concurrency mechanisms.
VII. Why Do Threads Need Synchronization Mechanisms?
Threads share process resources and can directly access the same data.
However, shared data also introduces contention problems.
1. What Is a Race Condition?
Suppose two threads execute at the same time:
counter++;
On the surface, this is just a simple increment operation.
But at the machine level, it usually involves multiple steps:
- Read counter.
- Add one to the value.
- Write the result back to counter.
If two threads execute at the same time, the following may happen:
Initial counter = 0
Thread A reads counter = 0
Thread B reads counter = 0
Thread A computes result = 1
Thread B computes result = 1
Thread A writes counter = 1
Thread B writes counter = 1
Final counter = 1
The expected result was 2, but the actual result is 1.
This is a data error caused by a race condition.
2. What Is a Critical Section?
A critical section is a region of code that accesses shared resources.
For example:
counter++;
If multiple threads may execute this code at the same time, appropriate synchronization protection is required.
3. Mutex Lock
A mutex lock ensures that only one thread enters the protected critical section at a time.
The POSIX threads library provides mutex interfaces.
Example:
#include <stdio.h>
#include <pthread.h>
int counter = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *worker(void *arg) {
for (int i = 0; i < 100000; i++) {
pthread_mutex_lock(&mutex);
counter++;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(void) {
pthread_t t1;
pthread_t t2;
pthread_create(&t1, NULL, worker, NULL);
pthread_create(&t2, NULL, worker, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("counter = %d\n", counter);
pthread_mutex_destroy(&mutex);
return 0;
}
Compile:
gcc mutex_demo.c -o mutex_demo -pthread
Run:
./mutex_demo
Expected result:
counter = 200000
The mutex ensures that updates to counter do not cause concurrent conflicts.
4. Common Thread Synchronization Mechanisms
| Synchronization Mechanism | Main Purpose | Typical Scenario |
|---|---|---|
| Mutex | Mutually exclusive access to shared resources | Protect shared variables |
| Semaphore | Control the number of concurrent resources | Connection pools, resource pools |
| Condition Variable | Wait for a specific condition to become true | Producer-consumer |
| Read-Write Lock | Distinguish read locks and write locks | Read-heavy, write-light |
| Atomic | Provide atomic operations | Counters, status flags |
| Barrier | Make multiple threads wait for the same phase | Parallel computing |