Table of contents
All of us know that if we make a program like test.js and run it on our computer becomes a process.
Program in a running state is a process.
Before understanding what is a thread, first of all, understand the processor and core.
Processor:-
It is an electronic circuit located in a computer that manages all the commands received from software and hardware executed on the computer.
The computer can have one or multiple processors.
Core:-
It is an electronic component placed inside the processor. It works on the simple instructions fed to it and it simply follows that step by step to execute and complete successfully.
The processor can hold one or multiple cores.
Thread:-
Threads are execution entities very much like processes but they are extensively very lightweight processes.
Thread supports the core to complete its task effectively. Thread is a virtual component that handles the task of the cores.
Let's write a very simple program.
let i = 0, sum = 0;
while( i <= 10 ) {
sum += i;
i++;
}
Now if we run the above code on a machine by let's say saving it as a JavaScript code then what will happen is, this program will be loaded in the memory and become a process and will be running on any one of the cores of our processor.
Assuming we have one octa-core processor. we will be having 7 other cores sitting idle.
So what the other program is doing? It is adding the first 10 natural numbers.
How about we try to divide our task of summing up the first 10 natural numbers between all of our 8 processor cores? Then there will be 8 processes running in different cores which will sum the things in a parallel fashion.
This kind of model is called the processor model.
Now there is something called thread mode.
In thread mode, we create 1 process with 8 threads and each thread does 1/8th of the given work. It will be equivalently fast as running it on 8 different processors.
One interesting fact about a thread is that all the thread maintains their call stack.
You might think that won't be slow to run 8 threads as compared to running the process on 8 different cores.
It won't be that slow, as threads are very lightweight on memory, the context switching is very fast compared to normal processes and threads can also communicate within themselves.