Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 31

Threads and Multithreading

• A thread is a single sequence stream within a process. Threads are


also called lightweight processes as they possess some of the
properties of processes. Each thread belongs to exactly one process.
• In an operating system that supports multithreading, the process can
consist of many threads. But threads can be effective only if the CPU
is more than 1 otherwise two threads have to context switch for that
single CPU.
Importance of threads in a OS
• Threads run in parallel improving the application performance. Each such thread
has its own CPU state and stack, but they share the address space of the process
and the environment.
• Threads can share common data so they do not need to use
inter-process communication. Like the processes, threads also have states like
ready, executing, blocked, etc.
• Priority can be assigned to the threads just like the process, and the highest
priority thread is scheduled first.
• Each thread has its own Thread Control Block (TCB). Like the process, a context
switch occurs for the thread, and register contents are saved in (TCB). As threads
share the same address space and resources, synchronization is also required for
the various activities of the thread.
Components of Threads

• These are the basic components of the Operating System.


• Stack Space
• Register Set
• Program Counter
Types of Thread in Operating System
• There are two types of threads
• User Level Thread
• Kernel Level Thread
User Level Threads

• User Level Thread is a type of thread that is not created using system calls. The kernel has no
work in the management of user-level threads. User-level threads can be easily implemented by
the user. In case when user-level threads are single-handed processes, kernel-level thread
manages them.
Merits of User-Level Threads
• Implementation of the User-Level Thread is easier than Kernel Level Thread.
• Context Switch Time is less in User Level Thread.
• User-Level Thread is more efficient than Kernel-Level Thread.
• Because of the presence of only Program Counter, Register Set, and Stack Space, it has a simple
representation.
Demerits of User-Level Threads
• There is a lack of coordination between Thread and Kernel.
• In case of a page fault, the whole process can be blocked.
Kernel Level Threads

• A kernel Level Thread is a type of thread that can recognize the Operating system
easily. Kernel Level Threads has its own thread table where it keeps track of the
system. The operating System Kernel helps in managing threads. Kernel Threads have
somehow longer context switching time. Kernel helps in the management of threads.
Merit of Kernel-Level Threads
• It has up-to-date information on all threads.
• Applications that block frequency are to be handled by the Kernel-Level Threads.
• Whenever any process requires more time to process, Kernel-Level Thread provides
more time to it.
• Demerit of Kernel-Level threads
• Kernel-Level Thread is slower than User-Level Thread.
• Implementation of this type of thread is a little more complex than a user-level
thread.
Difference Between Process and Thread

• The primary difference is that threads within the same process run in
a shared memory space, while processes run in separate memory
spaces.
• Threads are not independent of one another like processes are, and
as a result, threads share with other threads their code section, data
section, and OS resources (like open files and signals).
• But, like a process, a thread has its own program counter (PC),
register set, and stack space.
Multithreading
• The idea is to achieve parallelism by dividing a process into multiple
threads.
• For example, in a browser, multiple tabs can be different threads.
• MS Word uses multiple threads: one thread to format the text,
another thread to process inputs, etc
• Multithreading is a technique used in operating systems to improve
the performance and responsiveness of computer systems.
• Multithreading allows multiple threads (i.e., lightweight processes) to
share the same resources of a single process, such as the
CPU, memory, and I/O devices.
Merits of Multithreading in the OS
• Responsiveness: If the process is divided into multiple threads, if one thread
completes its execution, then its output can be immediately returned.
• Faster context switch: Context switch time between threads is lower
compared to the process context switch. Process context switching requires
more overhead from the CPU.
• Effective utilization of multiprocessor system: If we have multiple threads
in a single process, then we can schedule multiple threads on multiple
processors. This will make process execution faster.
• Resource sharing: Resources like code, data, and files can be shared among
all threads within a process. Note: Stacks and registers can’t be shared
among the threads. Each thread has its own stack and registers.
• Communication: Communication between multiple threads is easier,
as the threads share a common address space. while in the process
we have to follow some specific communication techniques for
communication between the two processes.
• Enhanced throughput of the system: If a process is divided into
multiple threads, and each thread function is considered as one job,
then the number of jobs completed per unit of time is increased, thus
increasing the throughput of the system.
SIGNAL SYSTEM CALLS
• A signal is a message or notification issued to your program by the
operating system or another application (or one of its threads). Each
signal is assigned a number between 1 and 31. Signals are devoid of
argument, and most of the time, their names are self-explanatory. For
instance, signal number 9 or SIGKILL notifies the program that it is
being attempted to be killed.
• There is a simple method for compiling a list of all the signals your
system supports. Simply type the kill -l command to see all the
allowed signals.
Signal as interrupt

• Signals disrupt your program in addition to being instructive.


• For example, one of the threads in your application must briefly
switch to signal handler mode in order to process a signal.
• As of the Linux kernel version 2.6, it should be noted that most signals
only interrupt one thread, as opposed to the previous practice of
interrupting the entire application.
• Additionally, a signal handler itself may be halted by a different signal.
Signal masks

• Each signal has one of three possible states:


• For the signal, we might have our own signal handler.
• The default handler may be used to handle a signal. Each signal has a
default handler job that it performs. For instance, your application will
be terminated by the SIGINT default handler.
• The signal could be overlooked. Signal blocking is another name for
ignoring a signal.
What signals are good for?

• There are various signal types, and each one denotes a different meaning.
Each signal’s designation is determined by its semantics. In other words,
you might wish to select what action should be connected to each of the
signals.
• You might determine that your application would print anything or draw
something on the screen in response to a certain signal. Most of the time, it
is your choice.
• There is, however, a standard norm for what each and every signal should
do. This accepted practice states that SIGINT should force your program to
end. It is in your best interest to maintain this as the SIGINT signal’s default
response. Usability is an issue. Nobody desires a non-interruptible program.
• Signals report exceptions: signals can also be used to suggest that
something unpleasant has transpired. For instance, the operating
system sends a SIGSEGV signal to your application when your
software creates a segmentation failure.
SOCKETS SYSTEM CALLS
• A socket is one endpoint of a two way communication link between two
programs running on the network.
• The socket mechanism provides a means of inter-process
communication (IPC) by establishing named contact points between
which the communication take place.
• Like ‘pipe’ is used to create pipes and sockets is created
using ‘socket’ system call. The socket provides
bidirectional FIFO Communication facility over the network.
• A socket connecting to the network is created at each end of the
communication. Each socket has a specific address. This address is
composed of an IP address and a port number.
• Socket are generally employed in client server applications. The server
creates a socket, attaches it to a network port addresses then waits
for the client to contact it. The client creates a socket and then
attempts to connect to the server socket. When the connection is
established, transfer of data takes place.
Types of Sockets
• Datagram Socket : This is a type of network which has connection less
point for sending and receiving packets. It is similar to mailbox. The
letters (data) posted into the box are collected and delivered
(transmitted) to a letterbox (receiving socket).
• Stream Socket In Computer operating system, a stream socket is type
of interprocess communications socket or network socket which
provides a connection-oriented, sequenced, and unique flow of data
without record boundaries with well defined mechanisms for creating
and destroying connections and for detecting errors. It is similar to
phone. A connection is established between the phones (two ends)
and a conversation (transfer of data) takes place.
ERROR HANDLING
• Although C does not provide direct support to error handling (or
exception handling), there are ways through which error handling can
be done in C. A programmer has to prevent errors in the first place
and test return values from the functions.
• A lot of C function calls return -1 or NULL or set an in case of an error
code as the global variable errno, so quick tests on these values are
easily done with an instance of ‘if statement’.
What is errno?

• errno is a global variable indicating the error occurred during any


function call and it is defined inside <errno.h> header file.
• When a function is called in C, a variable named errno is
automatically assigned a code (value) which can be used to identify
the type of error that has been encountered. Different codes (values)
for errno mean different types of errors.
A list of a few different errno values and
their corresponding meaning
#include <errno.h>
#include <stdio.h>
int main()
{
// If a file is opened which does not exist,
// then it will be an error and corresponding
// errno value will be set
FILE* fp;

// opening a file which does not exist


fp = fopen(“mcsjkuat3.txt", "r");
printf("Value of errno: %d\n", errno);
return 0;
}
Different Methods for Error Handling in C

• Different methods are used to handle different kinds of errors in C.


Some of the commonly used methods are:
• perror()
• strerr()
• ferror()
• feof()
• clearerr()
• Exit Status
• Divide by Zero Error
perror()
• The perror() function is used to show the error description. It displays
the string you pass to it, followed by a colon, a space, and then the
textual representation of the current errno value.

• Syntax
void perror(const char *str);
• str: It is a string containing a custom message to be printed before the
error message itself.
// C implementation to see how perror() function is used to
// print the error messages.
#include <errno.h>
#include <stdio.h>
#include <string.h>
int main()
{ FILE* fp;
// If a file is opened which does not exist,
// then it will be an error and corresponding
// errno value will be set
fp = fopen(" jkia3.txt ", "r");
// opening a file which does
// not exist.
printf("Value of errno: %d\n ", errno);
perror("Message from perror");
return 0;
}
strerror()

• The strerror() function is also used to show the error description. This
function returns a pointer to the textual representation of the current
errno value.

• Syntax
char *strerror(int errnum);
• // C implementation to see how strerror() function is used
• // to print the error messages.
• #include <errno.h>
• #include <stdio.h>
• #include <string.h>

• int main()
• {
• FILE* fp;

• // If a file is opened which does not exist,


• // then it will be an error and corresponding
• // errno value will be set
• fp = fopen(" jkia123.txt ", "r");

• // opening a file which does


• // not exist.
• printf("Value of errno: %d\n", errno);
• printf("The error message is : %s\n", strerror(errno));

• return 0;
• }
ferror()

• The ferror() function is used to check whether an error occurred


during a file operation.
• Syntax
int ferror(FILE *stream);
• Parameters
stream: It is the pointer that points to the FILE for which we want to
check the error.
• Return Value
It returns a non-zero value if an error occurred, otherwise it returns 0.

You might also like