Process vs Thread
By
Dr. Tausif Diwan
A C program execution
Here it is a Program Here it is a Process Processor
i.e passive entity i.e active entity
C program Compile Executable Data
HDD RAM 2
Process structure
1. Int a,b,c,Result
2. Int call_func(int a, int b)
3. { A process is program under execution
4. Int x = a*b A process is more than program code
5. Int y = a-b It also includes
6. Return (y+x) ● Process ID
7. } ● program counter
8. Int main() ● registers
9. { ● state
10. Read a,b ● open files pointers
11. Result = Call_func(a,b) ● children
12. print(Result) ● Current directory, etc.
13. Return 0
14. }
3
Process in Memory
1. Int a,b,c,Result Max Stack
2. Int call_func(int a, int b) Process stack contains
3. { Temporary
Heap is the data such as
memory which
4. Int x = a*b function
isData parameters,
dynamically
section allocated
which
5. Int y = a-b return
during address,
process
A program
contains and
code
global local
runtime
is stored
variables
variables
in a text section
6. Return (y+x)
7. }
8. Int main() Heap
9. {
Data A program counter register keep
10. Read a,b,c,Result track current instruction being
11. Result = Call_func(a,b) executed and processor registers
0 Text
12. print(Results) holds the variable values
13. Return main Process Address Space
14. }
4
Memory layout of a C program
#include<stdio.h>
#include<stdlib.h>
Argc, argv
int x;
Stack int y = 15;
int main(int argc, int *argv[])
{
int *value;
int i;
values = (int *)malloc(sizeof(int) * 5);
Heap for(int i = 0; i < 5; i++)
uninitialized data {
values[i] = i;
Initialized data }
return 0;
Text
}
5
Limitations of Process
• Process address space is bigger in size
• To create many processes requires large space in memory
• Creating many processes is cumbersome
6
What is thread?
● Thread is a light weight process
● Multiple threads can be spawned inside a process
● Threads can be executed in parallel
● Instead of creating multiple heavy processes we create multiple threads
within a process Process
Thread 0 Thread 1 Thread 2 Thread 3 Thread 4
Single vs multi threaded process
Code Data Heap Code Data Heap
Registers Stack Registers Registers Registers
Stack Stack Stack
Single threaded process Multi-threaded process 8
Process execution
Loop from a C program
for(int i = 0; i < 100; i++)
Process Core 0 Core 1
{
A[i] = A[i] + 5;
}
Core 2 Core 3
9
Multiple process execution
Loop from a C program Process 1
Process 0
for(int i = 0; i < 25 i++)
{ Core 0 Core 1
for(int
A[i] = A[i]i += 5;
25; i < 50; i++)
} {
for(int
A[i] = A[i]i += 5;
50; i < 75; i++) Process 2
Core 2 Core 3
} {
A[i] = A[i]i += 5;
for(int 75; i < 100; i++)
} {
A[i] = A[i] + 5; Process 3
}
10
Multi Threaded execution
Loop from a C program Thread 1
Thread 0
for(int i = 0; i < 25 i++)
{ Core 0 Core 1
for(int
A[i] = A[i]i += 5;
25; i < 50; i++)
} {
for(int
A[i] = A[i]i += 5;
50; i < 75; i++) Thread 2
Core 2 Core 3
} {
A[i] = A[i]i += 5;
for(int 75; i < 100; i++)
} {
A[i] = A[i] + 5; Thread 3
}
11