﻿---
title: Process & Thread
date: 2024-03-04
excerpt: An introduction to processes and threads
tags:
  - OS
  - Linux
  - Process
  - Thread
cover: https://assets.vluv.space/cover/OS/ProcessVsThread.webp
updated: 2026-07-08 21:23:13
lang: en
i18n:
  cn: /ProcessvsThread
  translation: 2
---

## Process

- A process is an instance of a program running in a computer.
- A process is an independent unit of execution in a computer program, including the complete set of instructions and the associated memory and resources.
- It is a program that is under execution.

Typical definitions of a process:

- A process is one execution of a program.
- A process is the activity that occurs when a program and its data execute sequentially on a processor.
- A process is the running of a program over a data set; it is an independent unit for resource allocation and scheduling by the system.

> [!info] Program vs Process
>
> Program vs Process: A program is a passive entity, such as a file containing a list of instructions stored on disk, whereas a process is an active entity, with a program counter specifying the next instruction to execute and a set of associated resources.
>
> **Differences between an executable program and a process**
>
> - A program is permanent; a process is temporary. A process is one execution of a program on a data set, it is created and destroyed, and its existence is transient.
> - A program is a static concept; a process is a dynamic one.
> - A process has concurrency; a program does not.
> - A process is the basic unit competing for computer resources; a program is not.
> - Processes and programs are not one-to-one:
>   - One program can correspond to multiple processes, i.e., multiple processes can execute the same program.
>   - One process can execute one or several programs.

### Features

- **Dynamic**: A process is essentially one execution of a process entity, so dynamism is its most fundamental feature. It "comes into being through creation, executes through scheduling, and dies through termination." A process entity therefore has a lifetime.
- **Concurrency**: Multiple process entities can reside in memory at the same time and run concurrently over a period of time.
- **Independence**: A process entity is a basic unit that can run independently, be allocated resources independently, and be scheduled independently.
- **Asynchronism**: Processes advance at their own independent, unpredictable speeds; that is, process entities run asynchronously.

### Components

A **process entity** includes:

- **Program Block**: The code that is to be executed.
- **Data Block**: The variables and data that are used by the program.
- **Stack**: The stack that is used to store the temporary data and function calls.
- **Process control block (PCB)**: It is a data structure that contains information about the process. It includes process state, process ID, CPU registers, CPU scheduling information, memory management information, and other information. It is used by the operating system to manage the process.

[[Ch2-1ProcessControl#进程控制块 PCB]]

### Process States

- **New**: The process has been created, but has not yet been admitted by the OS as an executable process; the program is still in secondary storage, while the PCB is in memory.
- **Ready**: The process is ready to be executed.
- **Running**: The process is currently being executed.
- **Blocked/Waiting**: The process is waiting for some event to occur.
- **Exit**: Released from execution by the OS due to halting or cancellation.

![Process States](https://assets.vluv.space/UESTC/OS/ProcessvsThread/ProcessvsThread-2024-03-04-13-43-46.webp)

When an event that triggers suspension occurs, a user may request to suspend itself, or a parent process may request to suspend its child; in these cases the suspend primitive `Suspend()` is used.
When an activation event occurs, the system uses the activation primitive `Active()` to activate the specified process. The activation primitive swaps the process from external storage into memory, then checks its state.

![Process States](https://assets.vluv.space/UESTC/OS/ProcessvsThread/ProcessvsThread-2024-03-04-14-00-16.webp)

The suspended state is also called the dormant state. A ready process that is suspended becomes suspended-ready; a blocked process that is suspended becomes suspended-blocked. A suspended process is kept on disk (external storage) and can only be scheduled for execution after being swapped back into memory.

![Process States](https://assets.vluv.space/UESTC/OS/ProcessvsThread/ProcessvsThread-2024-03-04-13-59-41.webp)

> [!attention] Suspend
>
> - Even if the event a process is waiting for has occurred, the process cannot execute as long as it is suspended. Only after it is resumed from the suspended state can it decide, based on its own readiness conditions (such as whether the awaited event has occurred), whether it can execute.
> - A process can be suspended by: itself, its parent process, or the OS. Only the process that suspended it can move it out of the suspended state.
>
> **Causes of Suspension**
>
> - A request from the terminal user.
> - A request from the parent process.
> - Load regulation. When a real-time system is heavily loaded, some unimportant processes are suspended to keep the system running normally.
> - The needs of the operating system. The OS may want to suspend certain processes in order to inspect resource usage during execution or to perform accounting.
>
> **Blocked VS Suspend**
>
> **Blocked**: A running process temporarily cannot continue **because of events such as an I/O request or a failed buffer allocation**. This triggers process scheduling: the OS assigns the processor to another ready process while the affected process stays paused. This state is generally called the blocked state.
> **Suspended**: The suspend operation is introduced for **the needs of the system and the user**. A suspended process is in a dormant state. If it was executing, it pauses; if it was ready, it temporarily does not accept scheduling.
>
> | Dimension                  | Blocked                                                        | Suspended                                                             |
> | -------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------- |
> | **CPU usage**              | Process pauses execution, does not occupy the CPU              | Process pauses execution, does not occupy the CPU                      |
> | **When it happens**        | Automatically when waiting for resources (e.g., I/O, semaphore) | Actively triggered by the user or OS for management purposes           |
> | **When it resumes**        | Automatically becomes ready once the awaited resource is ready  | The suspending party (user or system) decides when to resume           |
> | **Where it resides**       | Always in memory                                                | Its memory is released after suspension; it is kept in external storage |
> | **Common scenarios**       | Waiting for I/O, waiting for a mutex                            | User pauses for debugging; system swaps out inactive processes under memory pressure |
> | **Scheduling eligibility** | Becomes ready and schedulable once the resource is satisfied    | Must first be resumed to the ready state before it can be scheduled    |

## Thread

- A thread is a basic unit of CPU utilization.
- It is a single sequence stream within a process.
- A thread is a lightweight process. It shares the same memory space and system resources with other threads in the same process.

Also known as a lightweight process, a thread is even lighter. Multiple threads can execute concurrently within the same process and share the process's resources, such as memory space, file handles, and network connections.

> [[Ch2-4Thread#线程概述]]

### Features

- **Lightweight**: Threads are lightweight compared to processes. It takes less time to create and terminate threads.
- **Shared resources**: Threads in the same process share the same memory space and system resources.
- **Efficiency**: Threads are more efficient than processes because they share the same memory space and system resources.

### Components

**TCB Components**

- **Tid**: A unique thread identifier in the process.

  > Like a process, each thread also has a thread ID. A process ID is unique across the whole system, whereas a thread ID is unique only within the process it belongs to.

- **Register set**: These are small storage areas that quickly hold and release data. They store intermediate values during execution.Including **Program counter** which keeps track of the execution of the thread, indicating the address of the next instruction to be executed.
- **Stack**: It is a data structure that stores temporary data like function parameters, return addresses, and local variables.

![](https://assets.vluv.space/UESTC/OS/ProcessvsThread/ProcessvsThread-2024-03-13-10-44-36.webp)

### Thread States

Like processes, threads also share resources and cooperate with one another under mutual constraints, so a thread's execution is also intermittent.
A running thread has the following 3 states:

- **Running**: The thread has obtained the CPU and is executing.
- **Ready**: The thread has all the conditions needed to run and can execute as soon as it obtains the CPU.
- **Blocked**: The thread is stalled by some event during execution and is in a paused state.

## Comparison

### Comparison

A **thread** has many of the characteristics of a traditional process, so it is also called a **Light-Weight Process**; accordingly, a traditional **process** is called a **Heavy-Weight Process**. A traditional process is equivalent to a task with only one thread.
In an operating system that supports threads, a process usually owns several threads, and at least one.

![](https://assets.vluv.space/UESTC/OS/Ch2-4Thread/Ch2-4Thread-2024-03-13-09-23-33.webp)

Below, threads and processes are compared in terms of scheduling, concurrency, system overhead, and resource ownership.

- **Scheduling**: In traditional operating systems, the process is the basic unit of both resource ownership and independent scheduling/dispatching. In operating systems with threads, the thread becomes the basic unit of scheduling and dispatching, while the process remains the basic unit of resource ownership.
- **Concurrency**: In an OS with threads, not only can processes execute concurrently, but multiple threads within one process can also execute concurrently. This gives the OS better concurrency, improving system resource utilization and throughput more effectively.
- **Resource ownership**: Generally, a thread does not own system resources itself (apart from a few indispensable ones), but it can access the resources of its owning process. That is, a process's code segment, data segment, and owned system resources, such as open files and I/O devices, can be shared by all threads in that process.
- **Independence**: Threads within the same process share the process's memory space and resources.
- **System overhead**: Switching threads only requires saving and restoring a small amount of register content, with no memory management operations involved. Because multiple threads in a process share the same address space, synchronization and communication are also easier between threads than between processes. In some operating systems, thread switching, synchronization, and communication require no intervention from the OS kernel.
- **Multiprocessor support**: A process can be split into multiple threads distributed across multiple processors for parallel execution, speeding up its completion.

**Linux Process/Thread Control Operations Comparison**

|         Function          |                  Thread                  |                                Process                                 |
| :-----------------------: | :--------------------------------------: | :--------------------------------------------------------------------: |
|          Create           |             `pthread_create`             |                             `fork,vfork`                               |
|           Exit            |              `pthread_exit`              |                                `exit`                                  |
|           Wait            |              `pthread_join`              |                          `wait`, `waitpid`                             |
|      Cancel/Terminate     |             `pthread_cancel`             |                               `abort`                                  |
|          Get ID           |             `pthread_self()`             |                              `getpid()`                                |
| Sync/Mutex/Communication  | Mutexes, condition variables, rwlocks    | Anonymous pipes, named pipes, signals, message queues, semaphores, shared memory |

### Java Example

Excerpted from [javaguide](https://javaguide.cn/cs-basics/operating-system/operating-system-basic-questions-01.html#%E8%BF%9B%E7%A8%8B%E5%92%8C%E7%BA%BF%E7%A8%8B%E7%9A%84%E5%8C%BA%E5%88%AB%E6%98%AF%E4%BB%80%E4%B9%88)

As the figure below shows, a process can contain multiple threads. The threads share the process's heap and method area (metaspace since JDK 1.8), but each thread has its own program counter, virtual machine stack, and native method stack.

![](https://assets.vluv.space/UESTC/OS/ProcessvsThread/ProcessvsThread-2024-03-04-14-13-53.webp)

The biggest difference between threads and processes is that processes are basically independent of one another, while threads are not necessarily so, since threads within the same process are very likely to affect each other.
Threads have low execution overhead but are less suited to resource management and protection; processes are the opposite.

### Why do we need threads when we already have processes?

Process switching is an expensive operation, while thread switching costs much less.
Threads are lighter; one process can create multiple threads.
Multiple threads can handle different tasks concurrently, making more effective use of multiprocessor and multicore machines. A process can only do one thing at a time; if it hits a blocking issue during execution, such as blocking I/O, it is suspended until the result returns.
Threads within the same process share memory and files, so they can communicate with each other without calling into the kernel.

### Why use multithreading?

**Overall**

**From the perspective of the computer's underlying layers**: A thread can be seen as a lightweight process and is the smallest unit of program execution; switching and scheduling between threads costs far less than between processes. Moreover, in the multicore CPU era, multiple threads can run simultaneously, which reduces the overhead of thread context switching.
**From the perspective of modern internet trends**: Today's systems routinely demand millions or even tens of millions of concurrent requests, and multithreaded concurrent programming is the foundation of high-concurrency systems. Using multithreading well can greatly improve a system's overall concurrency and performance.

**At the hardware level**

**Single-core era**: In the single-core era, multithreading was mainly about improving how efficiently a single process used the CPU and the I/O system. Suppose only one Java process is running: when we make an I/O request, if the Java process has only one thread and that thread blocks on I/O, the entire process blocks. Only one of the CPU and the I/O device is working, so roughly speaking the system's overall efficiency is only 50%. With multiple threads, when one thread blocks on I/O, other threads can keep using the CPU, improving the Java process's overall use of system resources.
**Multicore era**: In the multicore era, multithreading is mainly about improving a process's ability to use multiple CPU cores. For example, if we need to compute a complex task with only one thread, only one CPU core will be used no matter how many cores the system has. If we create multiple threads instead, they can be mapped onto multiple underlying CPUs. When the task's threads have no resource contention, execution efficiency improves significantly, roughly to (single-core execution time / number of CPU cores).

## Ref

[CITS2002 Systems Programming, Lecture 7,](https://teaching.csse.uwa.edu.au/units/CITS2002/lectures/lecture07/singlepage.html)
