Understanding Processes, Threads and CPU Cores
Hello, everyone ๐
In this article you will read about Processes, Threads, CPU Cores and how these are related.
What is a Process?
A set of instruction given to Computer to perform a task is called Computer Program. When this program is executed, Operating System (OS) loads the program into memory and provides required resources like registers, program counter, stack and heap to complete the task. A register is a temporary storage area built into a CPU that holds an instruction, storage address and other data needed by a process. The Program Counter is part of CPU that keeps track of next instruction to be executed. Stack and Heap are data structure stores variables and functions of a program in memory. So,
Program + Resources required to execute = A Process
What is a Thread?
Thread is the unit of execution within a process performing a task. It is also called lightweight process. A process can have single or multiple threads. In single-threaded process both the process and thread are same. When a process starts, memory and resources are allocated. Each thread in the process shares that memory and resources, except the stack. Every thread has it's own stack. A single-threaded process can perform one task at a time, but a multi-threaded process can perform multiple tasks at the same time.
CPU Cores
Central Processing Unit (CPU) is capable of running single process or thread at any given time. Back in Pentium 4 single core processor days the computer executes only one process or thread at a time, and performs effective switching (context switching) from one thread to another in negligible time that gives an illusion of simultaneous execution, this is called Concurrency. It is not possible to perform a true parallel execution of threads in single core processor. If a process or thread runs in infinite loop, the whole computer becomes unresponsive.
Now, how can we make a processor to truly perform multiple tasks parallelly? You are right, add more CPUs. All the modern processors are multi-core processors, meaning, a single physical processor will have more than one CPUs in it, is called cores. Multi-core processors are capable to run more than one process or thread at the same time. Example, a quad-core processor has 4 CPU cores, it can run 4 processes or threads at the same time in parallel is called Parallelism. Here if a thread runs in infinite loop, it doesn't block the whole computer as we still have 3 CPU cores continue to execute. Using a multi-core processor naturally increases the performance of a program and does natively support Parallelism.
Conclusion
As a programmer it is important to know the difference between Processes and Threads, and how they are treated in single-core vs multi-core processor. Which helps in making a calculative decision when designing a program.
Thanks for reading! Stay tuned ๐