0% found this document useful (0 votes)
14 views

Threads OS

Threads

Uploaded by

2022uee1010
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Threads OS

Threads

Uploaded by

2022uee1010
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Multithreaded Programming

A computer program becomes a process when it is loaded from some store


into the computer's memory and begins execution. A process can be
executed by a processor or a set of processors. A process description in
memory contains vital information such as the program counter, registers,
variable stores, file handles, signals, and so forth.
• Definition
A thread is a sequence of such instructions within a program that can be
executed independently of other code. A thread is a single sequence stream
within in a process. Because threads have some of the properties of
processes, they are sometimes called lightweight processes.
• In a process, threads allow multiple executions of streams. In many
respect, threads are popular way to improve application through
parallelism.
• Each thread has its own stack.
• Since thread will generally call different procedures and thus a different
execution history. This is why thread needs its own stack.
• An operating system that has thread facility, the basic unit of CPU
utilization is a thread. A thread has a program counter (PC), a register set,
and a stack space. Threads are not independent of one other like
processes as a result threads shares with other threads their code
section, data section, OS resources , such as open files and signals.
Motivation
• Threads are very useful in modern programming whenever a process has
multiple tasks to perform independently of the others.
• This is particularly true when one of the tasks may block, and it is desired
to allow the other tasks to proceed without blocking.
• For example in a word processor, a background thread may check spelling
and grammar while a foreground thread processes user input (
keystrokes ), while yet a third thread loads images from the hard drive,
and a fourth does periodic automatic backups of the file being edited.
Difference between Process and Thread
S.N. Process Thread

1 Process is heavy weight or resource intensive. Thread is light weight, taking lesser resources than
a process.
2 Process switching needs interaction with Thread switching does not need to interact with
operating system. operating system.
3 In multiple processing environments, each All threads can share same set of open files, child
process executes the same code but has its own processes.
memory and file resources.

4 If one process is blocked, then no other process While one thread is blocked and waiting, a second
can execute until the first process is unblocked. thread in the same task can run.

5 Multiple processes without using threads use Multiple threaded processes use fewer resources.
more resources.
6 In multiple processes each process operates One thread can read, write or change another
independently of the others. thread's data.
Why Threads?
• A process with multiple threads make a great server e.g printer server, web
server.
• Because threads can share common data, they do not need to use interprocess
communication.
• Threads can take advantage of multiprocessors.
Threads are inexpensive in the sense that
• They only need a stack and storage for registers
• Threads use very little resources of an operating system in which they are
working. That is, threads do not need new address space, global data, program
code or operating system resources.
• Context switching are fast when working with threads. The reason is that we
only have to save and/or restore PC, SP and registers.
The biggest drawback is that there is no protection between threads.
Benefits
• Responsiveness
One thread may provide rapid response while other threads are blocked or slowed
down doing intensive calculations.
• Resource sharing
By default threads share common code, data, and other resources, which allows
multiple tasks to be performed simultaneously in a single address space.
• Economy
Creating and managing threads ( and context switches between them ) is much
faster than performing the same tasks for processes.
• Scalability
Utilization of multiprocessor architectures - A single threaded process can only run
on one CPU, no matter how many may be available, whereas the execution of a
multi-threaded application may be split amongst available processors.
Multicore Programming
Types of Thread
User threads, are above the kernel and without kernel support. These are
the threads that application programmers use in their programs.
• User-level threads implement in user-level libraries, rather than via
systems calls, so thread switching does not need to call operating
system and to cause interrupt to the kernel. In fact, the kernel knows
nothing about user-level threads and manages them as if they were
single-threaded processes.
• Thread management done by user-level threads library
Three primary thread libraries:
• POSIX Pthreads
• Win32 threads
• Java threads
Kernel threads are supported within the kernel of the OS itself. All modern
OSs support kernel level threads, allowing the kernel to perform multiple
simultaneous tasks and/or to service multiple kernel system calls
simultaneously.
• In this method, the kernel manages the threads. No runtime system is
needed in this case. Instead of thread table in each process, the kernel
has a thread table that keeps track of all threads in the system. In
addition, the kernel also maintains the traditional process table to keep
track of processes. Operating Systems kernel provides system call to
create and manage threads.
Multithreading Models
• How user-level threads are mapped to kernel ones.

• Many-to-One: Examples:
GNU Portable Threads
• One-to-One: Examples
Windows NT/XP/2000
Linux
• Many-to-Many
Many-To-One Mode
• In the many-to-one model, many user-level threads are all mapped onto
a single kernel thread.
• Thread management is handled by the thread library in user space,
which is efficient in nature.
One-To-One Model
• The one-to-one model creates a separate kernel thread to handle each
and every user thread.
• Most implementations of this model place a limit on how many threads
can be created.
• Linux and Windows from 95 to XP implement the one-to-one model for
threads.
Many-To-Many Model
• The many-to-many model multiplexes any number of user threads onto an
equal or smaller number of kernel threads, combining the best features of
the one-to-one and many-to-one models.
• Users can create any number of the threads.
• Blocking the kernel system calls does not block the entire process.
• Processes can be split across multiple processors.
Thread Libraries
• Thread libraries provide programmers with an API for creating and
managing threads.
• Thread libraries may be implemented either in user space or in kernel
space. The former involves API functions implemented solely within user
space, with no kernel support. The later involves system calls, and
requires a kernel with thread library support.
• There are three main thread libraries in use today:
• POSIX Pthreads - may be provided as either a user or kernel library, as an
extension to the POSIX standard.
• Win32 threads - provided as a kernel-level library on Windows systems.
• Java threads - Since Java generally runs on a Java Virtual Machine, the
implementation of threads is based upon whatever OS and hardware the JVM is
running on, i.e. either Pthreads or Win32 threads depending on the system.
Pthread Routines

pthread_create (thread, attr, start_routine, arg)


pthread_exit (status)
pthread_cancel (thread)
pthread_attr_init (attr)
pthread_attr_destroy (attr)

int pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(void *), void *arg);
• In main() we declare a variable called thread_id, which is of type
pthread_t, which is an integer used to identify the thread in the
system. After declaring thread_id, we call pthread_create() function
to create a thread.
• pthread_create() takes 4 arguments.
• The first argument is a pointer to thread_id which is set by this function.
• The Second argument is the scheduling parameter (priority etc. ) Default
parameter is NULL.
• The third argument is name of function to be executed for the thread to be
created.
The fourth argument is used to pass arguments to thread.

• The pthread_join() function for threads is the equivalent of wait() for


processes. A call to pthread_join blocks the calling thread until the
thread with identifier equal to the first argument terminates.
Thread Creation Program
#include<stdio.h>
#include<pthread.h>
int main ()
Pthread_t thread[2];
static void *function1(void * a) {
{ Pthread_create(&thread[0],NULL,function1,NULL);
int i; Pthread_create(&thread[1],NULL,function2,NULL);
for(i=0;i<10;i++) pthread_exit(NULL);
{
return 1;
printf(“\n thread 1 says=%d”,i)
}
sleep(2);
}}
static void *function2(void * b)
{
int i;
for(i=0;i<5;i++)
{
printf(“\n thread 2 says=%d”,i)
sleep(5);
}}
Thread Creation Program
#include <stdio.h>
#include <stdlib.h> pthread_join( thread1, NULL);
#include <pthread.h>
pthread_join( thread2, NULL);
void *print_message_function( void *ptr );

main() printf("Thread 1 returns: %d\n",iret1);


{ printf("Thread 2 returns: %d\n",iret2);
pthread_t thread1, thread2;
char *message1 = "Thread 1"; exit(0);
char *message2 = "Thread 2"; }
int iret1, iret2;

/* Create independent threads each of which will execute function */ void *print_message_function( void *ptr )
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) {
message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*)
char *message;
message2); message = (char *) ptr;
printf("%s \n", message);
}
How to Compile thread program
gcc -pthread filename.c
(To link pthread library with the program)

./a.out
Stopping a thread
Sometimes an application may wish to stop a thread that is currently
executing. The function pthread_cancel can help us accomplish this.

int pthread_cancel(pthread_t thread);

The only argument to pthread_cancel is the thread identifier for the


thread to be cancelled. It returns zero if successful, or an error code
otherwise.

You might also like