0% found this document useful (0 votes)
3 views15 pages

Process and Threads

Uploaded by

Disha Deshmukh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views15 pages

Process and Threads

Uploaded by

Disha Deshmukh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

States of a Process in Operating Systems

States of a process are as


following:

• New (Create) – In this step, the process is about to be created but not yet
created, it is the program which is present in secondary memory that will
be picked up by OS to create the process.
• Ready – New -> Ready to run. After the creation of a process, the process
enters the ready state i.e. the process is loaded into the main memory. The
process here is ready to run and is waiting to get the CPU time for its
execution. Processes that are ready for execution by the CPU are
maintained in a queue for ready processes.
• Run – The process is chosen by CPU for execution and the instructions
within the process are executed by any one of the available CPU cores.
• Blocked or wait – Whenever the process requests access to I/O or needs
input from the user or needs access to a critical region(the lock for which
is already acquired) it enters the blocked or wait state. The process
continues to wait in the main memory and does not require CPU. Once the
I/O operation is completed the process goes to the ready state.
• Terminated or completed – Process is killed as well as PCB is deleted.
• Suspend ready – Process that was initially in the ready state but was
swapped out of main memory(refer Virtual Memory topic) and placed
onto external storage by scheduler is said to be in suspend ready state.
The process will transition back to ready state whenever the process is
again brought onto the main memory.
• Suspend wait or suspend blocked – Similar to suspend ready but uses
the process which was performing I/O operation and lack of main memory
caused them to move to secondary memory. When work is finished it may
go to suspend ready.
CPU and I/O Bound Processes: If the process is intensive in terms of CPU
operations then it is called CPU bound process. Similarly, If the process is intensive
in terms of I/O operations then it is called I/O bound process. Types of schedulers:
1. Long term – performance – Makes a decision about how many processes
should be made to stay in the ready state, this decides the degree of
multiprogramming. Once a decision is taken it lasts for a long time hence
called long term scheduler.
2. Short term – Context switching time – Short term scheduler will decide
which process to be executed next and then it will call dispatcher. A
dispatcher is a software that moves process from ready to run and vice
versa. In other words, it is context switching.
3. Medium term – Swapping time – Suspension decision is taken by
medium term scheduler. Medium term scheduler is used for swapping that
is moving the process from main memory to secondary and vice versa.
Multiprogramming – We have many processes ready to run. There are two types of
multiprogramming:
1. Pre-emption – Process is forcefully removed from CPU. Pre-emption is
also called as time sharing or multitasking.
2. Non pre-emption – Processes are not removed until they complete the
execution.
Degree of multiprogramming – The number of processes that can reside in the
ready state at maximum decides the degree of multiprogramming, e.g., if the degree
of programming = 100, this means 100 processes can reside in the ready state at
maximum.

Process Table and Process Control Block (PCB)


While creating a process the operating system performs several operations. To
identify the processes, it assigns a process identification number (PID) to each
process. As the operating system supports multi-programming, it needs to keep
track of all the processes. For this task, the process control block (PCB) is used to
track the process’s execution status. Each block of memory contains information
about the process state, program counter, stack pointer, status of opened files,
scheduling algorithms, etc. All these information is required and must be saved
when the process is switched from one state to another. When the process makes a
transition from one state to another, the operating system must update information
in the process’s PCB.
A process control block (PCB) contains information about the process, i.e. registers,
quantum, priority, etc. The process table is an array of PCB’s, that means logically
contains a PCB for all of the current processes in the system.

• Pointer – It is a stack pointer which is required to be saved when the


process is switched from one state to another to retain the current
position of the process.
• Process state – It stores the respective state of the process.
• Process number – Every process is assigned with a unique id known as
process ID or PID which stores the process identifier.
• Program counter – It stores the counter which contains the address of
the next instruction that is to be executed for the process.
• Register – These are the CPU registers which includes: accumulator, base,
registers and general purpose registers.
• Memory limits – This field contains the information about memory
management system used by operating system. This may include the page
tables, segment tables etc.
• Open files list – This information includes the list of files opened for a
process.
Miscellaneous accounting and status data – This field includes information about
the amount of CPU used, time constraints, jobs or process number, etc.
The process control block stores the register content also known as execution
content of the processor when it was blocked from running. This execution content
architecture enables the operating system to restore a process’s execution context
when the process returns to the running state. When the process makes a transition
from one state to another, the operating system updates its information in the
process’s PCB. The operating system maintains pointers to each process’s PCB in a
process table so that it can access the PCB quickly.
Process Schedulers in Operating System
Process scheduling is the activity of the process manager that handles the removal
of the running process from the CPU and the selection of another process on the
basis of a particular strategy.
Process scheduling is an essential part of a Multiprogramming operating system.
Such operating systems allow more than one process to be loaded into the
executable memory at a time and the loaded process shares the CPU using time
multiplexing.
There are three types of process schedulers.

1. Long Term or job scheduler:


It brings the new process to the ‘Ready State’. It controls the Degree of
Multi-programming, i.e., the number of processes present in a ready state
at any point in time. It is important that the long-term scheduler make a
careful selection of both I/O and CPU-bound processes. I/O-bound tasks
are which use much of their time in input and output operations while
CPU-bound processes are which spend their time on the CPU. The job
scheduler increases efficiency by maintaining a balance between the two.
They operate at a high level and are typically used in batch-processing
systems.

2. Short-term or CPU scheduler:


It is responsible for selecting one process from the ready state for
scheduling it on the running state. Note: Short-term scheduler only selects
the process to schedule it doesn’t load the process on running. Here is
when all the scheduling algorithms are used. The CPU scheduler is
responsible for ensuring there is no starvation owing to high burst time
processes.
The dispatcher is responsible for loading the process selected by the
Short-term scheduler on the CPU (Ready to Running State) Context
switching is done by the dispatcher only. A dispatcher does the following:
1. Switching context.
2. Switching to user mode.
3. Jumping to the proper location in the newly loaded program.
3. Medium-term scheduler:
It is responsible for suspending and resuming the process. It mainly does
swapping (moving processes from main memory to disk and vice versa).
Swapping may be necessary to improve the process mix or because a
change in memory requirements has overcommitted available memory,
requiring memory to be freed up. It is helpful in maintaining a perfect
balance between the I/O bound and the CPU bound. It reduces the degree
of multiprogramming.
Some other Schedulers:
• I/O schedulers: I/O schedulers are incharge of managing the execution of
I/O operations such as reading and writing to discs or networks. They can
use various algorithms to determine the order in which I/O operations are
executed, such as FCFS (First-Come, First-Served) or RR (Round Robin).
• Real-time schedulers: In real-time systems, real-time schedulers ensure
that critical tasks are completed within a specified time frame. They can
prioritize and schedule tasks using various algorithms such as EDF
(Earliest Deadline First) or RM (Rate Monotonic).

Process: Processes are basically the programs that are dispatched from the
ready state and are scheduled in the CPU for execution. PCB(Process Control
Block) holds the concept of process. A process can create other processes
which are known as Child Processes. The process takes more time to terminate
and it is isolated means it does not share the memory with any other process.
The process can have the following states new, ready, running, waiting,
terminated, and suspended.
Thread: Thread is the segment of a process which means a process can have
multiple threads and these multiple threads are contained within a process. A
thread has three states: Running, Ready, and Blocked.
The thread takes less time to terminate as compared to the process but unlike
the process, threads do not isolate.
Process vs Thread

Difference between Process and Thread:


[Link] Process Thread

Process means any program is


1. in execution. Thread means a segment of a process.

The process takes more time to


2. terminate. The thread takes less time to terminate.

3. It takes more time for creation. It takes less time for creation.

It also takes more time for


4. context switching. It takes less time for context switching.

The process is less efficient in Thread is more efficient in terms of


5. terms of communication. communication.
[Link] Process Thread

We don’t need multi programs in action for


Multiprogramming holds the multiple threads because a single process
6. concepts of multi-process. consists of multiple threads.

7. The process is isolated. Threads share memory.

The process is called the A Thread is lightweight as each thread in a


8. heavyweight process. process shares code, data, and resources.

Process switching uses an Thread switching does not require calling an


interface in an operating operating system and causes an interrupt to the
9. system. kernel.

If one process is blocked then


it will not affect the execution If a user-level thread is blocked, then all other
10. of other processes user-level threads are blocked.

The process has its own Thread has Parents’ PCB, its own Thread
Process Control Block, Stack, Control Block, and Stack and common Address
11. and Address Space. space.

Since all threads of the same process share


address space and other resources so any
Changes to the parent process changes to the main thread may affect the
12. do not affect child processes. behavior of the other threads of the process.

No system call is involved, it is created using


13. A system call is involved in it. APIs.

The process does not share


14. data with each other. Threads share data with each other.

Note: In some cases where the thread is processing a bigger workload


compared to a process’s workload then the thread may take more time to
terminate. But this is an extremely rare situation and has fewer chances to
occur.
S.
No. Parameters User Level Thread Kernel Level Thread

Kernel threads are


User threads are implemented implemented by Operating
1. Implemented by by users. System (OS).

Operating System doesn’t Kernel threads are recognized


2. Recognize recognize user level threads. by Operating System.

Implementation of User Implementation of Kernel


3. Implementation threads is easy. thread is complicated.

Context switch
4. time Context switch time is less. Context switch time is more.

Hardware Context switch requires no


5. support hardware support. Hardware support is needed.

If one user level thread If one kernel thread perform


performs blocking operation blocking operation then
Blocking then entire process will be another thread can continue
6. operation blocked. execution.

Multithread applications
cannot take advantage of
7. Multithreading multiprocessing. Kernels can be multithreaded.

User level threads can be Kernel level threads take


Creation and created and managed more more time to create and
8. Management quickly. manage.

Operating Any operating system can Kernel level threads are


9. System support user-level threads. operating system-specific.

The thread library contains The application code does not


Thread the code for thread creation, contain thread management
10. Management message passing, thread code. It is merely an API to
S.
No. Parameters User Level Thread Kernel Level Thread

scheduling, data transfer and the kernel mode. The


thread destroying Windows operating system
makes use of this feature.

Example: Java thread, POSIX


11. Example threads. Example: Window Solaris.

• User Level Threads • Scheduling of


are simple and multiple threads
quick to create. that belong to
• Can run on any same process on
operating system different
• They perform processors is
better than kernel possible in kernel
threads since they level threads.
don’t need to make • Multithreading can
system calls to be there for kernel
create threads. routines.
• In user level • When a thread at
threads, switching the kernel level is
between threads halted, the kernel
does not need can schedule
kernel mode another thread for
12. Advantages privileges. the same process.

• Transferring
• Multithreaded control within a
applications on process from one
user-level threads thread to another
cannot benefit from necessitates a
multiprocessing. mode switch to
• If a single user- kernel mode.
level thread • Kernel level
performs a threads takes more
blocking operation, time to create and
the entire process is manage than user
13. Disadvantages halted. level threads.
In this post we discuss the use of pthread_create function create threads in linux. Various
program to create threads in Linux are discussed below that shows how to create threads,
how to pass input to thread and how to return value from thread.

Syntax
#include<pthread.h>

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,

void *(*start_routine) (void *), void arg);

The first parameter is the buffer which will contain the ID of the new thread, if
pthread_create is successful. The second parameter specifies the attributes of the thread.
This parameter is generally NULL until you want to change the default settings. The third
parameter is the name the function which the thread will execute. Hence, everything that
you want the thread to do should be defined in this function. Lastly, the fourth parameter is
the input to the function in the third parameter. If the function in the third parameter does
not take any input then the fourth parameter is NULL.

Program 1: Program to create threads in linux. Thread prints 0-4 while the main process prints 20-
24

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
void *thread_function(void *arg);
int i,j;
int main() {
pthread_t a_thread; //thread declaration
pthread_create(&a_thread, NULL, thread_function, NULL);
//thread is created
pthread_join(a_thread, NULL); //process waits for thread to finish
. //Comment this line to see the difference
printf("Inside Main Program\n");
for(j=20;j<25;j++)
{
printf("%d\n",j);
sleep(1);
}
}
void *thread_function(void *arg) {
// the work to be done by the thread is defined in this function
printf("Inside Thread\n");
for(i=0;i<5;i++)
{
printf("%d\n",i);
sleep(1);
}
}

Note: To compile any program which involves creation of thread(s) use pthread library
(lpthread)
Suppose the above program is named “Thread.c”, then to compile write
$gcc Thread.c -lpthread
To run the command remains same
$./[Link]

Output

Inside Main Program

20

21

22

23

24
How it works?

pthread_create() creates a new thread which starts to execute thread_function. This function
creates a loop which prints 0-4. The sleep function makes the thread go to sleep after each
digit is printed. pthread_join() makes the main function wait until the newly created thread
finishes its execution. So the control returns to the main function only when the thread
finishes. Then the main function prints “Inside Main program” and executes the loop from
20-24.

How a thread returns a value to the main process?


pthread_exit() is used to return a value from the thread back to the main process. The
program below shows this. The program also shows how to pass value to a thread from the
main process.

Program 2: Program to create a thread. The thread prints numbers from zero to n, where value of n
is passed from the main process to the thread. The main process also waits for the thread to finish
first and then prints from 20-24.

#include<stdio.h>

#include<stdlib.h>

#include<unistd.h>

#include<pthread.h>

#include<string.h>

void *thread_function(void *arg);

int i,n,j;

int main() {

char *m="5";

pthread_t a_thread; //thread declaration

void *result;
pthread_create(&a_thread, NULL, thread_function, m); //thread is
created

pthread_join(a_thread, &result);

printf("Thread joined\n");

for(j=20;j<25;j++)

printf("%d\n",j);

sleep(1);

printf("thread returned %s\n",(char *)result);

void *thread_function(void *arg) {

int sum=0;

n=atoi(arg);

for(i=0;i<n;i++)
{
printf("%d\n",i);
sleep(1);
}
pthread_exit("Done"); // Thread returns "Done"
}

How it works?

When we call pthread_create() function a value if passed to the thread by passing that value
as the fourth parameter of the pthread_create() function.
How to pass multiple values to a thread using
structure?
Program 3: Program to create a thread. The thread is passed more than one input from the main
process. For passing multiple inputs we need to create structure and include all the variables that
are to be passed in this structure.

#include<stdio.h

#include<pthread.h>

struct arg_struct { //structure which contains multiple variables


that are to passed as input to the thread

int arg1;

int arg2;

};

void *arguments(void *arguments)

struct arg_struct *args=arguments;

printf("%d\n", args -> arg1);

printf("%d\n", args -> arg2);

pthread_exit(NULL);

int main()
{
pthread_t t;
struct arg_struct args;
args.arg1 = 5;
args.arg2 = 7;
pthread_create(&t, NULL, arguments, &args);
//structure passed as 4th argument
pthread_join(t, NULL); /* Wait until thread is finished */
}

Note: Just as above we can also pass an array to a thread.

You might also like