Process and Thread

Yuyang 前端小白🥬

Process and Thread

What is process and thread?And what is the difference between them?In this article, we will discuss the concept of process and thread.To better understand the concept of process and thread, we need to understand the concept of program.

What program is

A program is a excutable file that is stored on disk and is loaded into memory when it is run.
When a program is loaded into memory, it becomes a process.

Process

Process is a program in execution. A process is an instance of a program running on a computer. When a program is executed, it is loaded into memory and becomes a process. A process is an independent entity to which system resources (such as CPU time and memory) are allocated. Each process is executed in a separate address space, and one process cannot access the variables and data structures of another process. If a process wishes to access another process’ resources, inter-process communications have to be used. These include pipes, files, sockets, and other forms.

image-20240818063319857

Thread

Thread is a basic unit of CPU utilization, consisting of a program counter, a stack, and a set of registers, (and a thread ID.) Each thread shares with other threads belonging to the same process its code section, data section, and other operating-system resources, such as open files and signals.

image-20240818063237021

How does the operating system manage processes and threads

This is handled by the context switching mechanism, which enables the CPU to switch rapidly from one thread to another. This is done by saving the context of the thread that is currently running and loading the saved context of the thread that is to be executed. The operating system is responsible for managing the execution of processes and threads, and it does this by scheduling them to run on the CPU.

image-20240818063447864

![image-20240818064017828](../../../../../Library/Application Support/typora-user-images/image-20240818064017828.png)

The thread switching is also need context switching, but the thread switching is faster than the process switching.

image-20240818064201566

Because the expansive cost of context switching, there also have some other ways, such as fiber, coroutine, etc.

image-20240818064530759

Thanks https://www.youtube.com/watch?v=4rLW7zg21gI .