SlideShare a Scribd company logo
THREAD LIBRARIES
• A thread library provides the programmer with an API for
creating and managing threads.
• There are two primary ways of implementing a thread library.
• First approach
– is to provide a library entirely in user space with no kernel
support.
– All code and data structures for the library exist in user
space which means that invoking a function in the library
results in a local function call in user space and not a
system call.
• Second approach
– is to implement a kernel-level library supported directly by
the operating system.
– In this case, code and data structures for the library exist in
kernel space.
• Three main thread libraries are in use today:
 POSIX Pthreads
 Windows Threads
 Java Threads
 Two general strategies for creating multiple threads:
 Asynchronous threading
 Synchronous threading
 In asynchronous threading, once the parent creates a
child thread, the parent resumes its execution, so that the
parent and child execute concurrently.
 Each thread runs independently of every other thread,
and the parent thread need not know when its child
terminates.
 Because the threads are independent, there is typically
little data sharing between threads.
• Synchronous threading occurs when the parent thread
creates one or more children and then must wait for all of
its children to terminate before it resumes —the so-called
fork-join strategy.
• Once each thread has finished its work, it terminates and
joins with its parent. Only after all of the children have
joined , the parent resume execution.
• Synchronous threading involves significant data sharing
among threads.
• For example, the parent thread may combine the results
calculated by its various children.
• The C program demonstrates the basic
Pthreads API for constructing a multithreaded
program that calculates the summation of a
non-negative integer in a separate thread.
• If N is 5, this function would represent the
summation of integers from 0 to 5, which is 15
Pthreads
#include <pthread.h>
#include <stdio.h> int sum; /* This data is shared by the thread(s) */
void *runner(void *param); /* Threads call this function */
int main(int argc, char *argv[])
{
pthread_t tid; /* The thread identifier */
pthread_attr_t attr; /* Set of thread attributes */
if (argc != 2)
{
fprintf(stderr, "usage: %s <integer value>n", argv[0]); return -1;
}
if (atoi(argv[1]) < 0)
{
fprintf(stderr, "%d must be >= 0n", atoi(argv[1]));
return -1;
} /* Get the default attributes */
pthread_attr_init(&attr);
/* Create the thread */
pthread_create(&tid, &attr, runner, argv[1]);
/* Wait for the thread to exit */
pthread_join(tid, NULL);
printf("sum = %dn", sum);
return 0;
} /* The thread will begin control in this function */
void *runner(void *param)
{
int i, upper = atoi(param);
sum = 0;
for (i = 1; i <= upper; i++)
sum += i;
pthread_exit(0);
}
• All Pthreads programs must include the pthread.h header file
• When creating a new thread, we typically specify a function
that the thread will run. This function is sometimes referred
to as the "runner function" or "thread function.“
• When this program begins, a single thread of control begins
in main().
• After some initialization, main() creates a second thread that
begins control in the runner() function.
• Both threads share the global data sum.
• pthread_t tid : Declares a variable tid of type pthread_t,
which is used to identify a thread.
• pthread_attr_t attr : Declares a variable attr of type
pthread_attr_t, which is used to store thread attributes.
if (argc != 2)
{
fprintf(stderr, "usage: %s <integer value>n", argv[0]);
return -1;
}
if (atoi(argv[1]) < 0)
{
fprintf(stderr, "%d must be >= 0n", atoi(argv[1]));
return -1;
}
this code block ensures that the program is provided with the correct
number of command-line arguments which are non-negative integer.
If these conditions are not met, the program prints an error message
and exits with a return code of -1, signaling an error state.
• A separate thread is created with the pthread
create() function call
• In addition to passing the thread identifier and
the attributes for the thread, we also pass the
name of the function where the new thread will
begin execution—in this case, the runner()
function.
• Last, we pass the integer parameter that was
provided on the command line, argv[1].
• At this point, the program has two threads:
– the initial (or parent) thread in main()
– the summation (or child) thread performing the
summation operation in the runner() function.
• pthread_join() Parent thread waits for the created
thread to finish before proceeding with the main
thread.
• printf("sum = %dn", sum): Prints the calculated sum
after the thread has finished.
• The summation thread will terminate when it calls
the function pthread exit().
• Once the summation thread has returned, the parent
thread will output the value of the shared data sum.
• Parent Thread (Main Thread):
– Initialize Attributes: pthread_attr_init(&attr);
– Create Thread: pthread_create(&tid, &attr,
runner, argv[1]);
– Wait for Thread to Finish: pthread_join(tid, NULL);
– Print Result: printf("sum = %dn", sum);
• Child Thread (runner function):
– Calculate Sum: for (i = 1; i <= upper; i++) sum += i;
– Exit Thread: pthread_exit(0);
A simple method for waiting on several threads using the
pthread join() function is to enclose the operation within a
simple for loop.
Windows Threads
• The technique for creating threads using the
Windows thread library is similar to the
Pthreads technique in several ways.
OPERATNG SYSTEM MODULE-2 PRESENTATION OS
• The program defines a global variable Sum to
store the sum of integers calculated by the
thread(s).
• The Summation function is the entry point for
the thread.
• It takes a parameter Param (a pointer to an
integer) and calculates the sum of integers
from 1 to the value pointed to by Param.
DWORD WINAPI Summation(LPVOID Param)
/* LPVOID is a generic pointer that indicates that the
pointer can point to data of any type */
{
DWORD Upper = *(DWORD*)Param;
/*retrieves that value from the memory location
pointed to by Param and storing it in the variable Upper
*/
for (DWORD i = 0; i <= Upper; i++)
Sum += i;
return 0;
}
int main(int argc, char *argv[])
{
DWORD ThreadId;
HANDLE ThreadHandle; declares a variable named ThreadHandle of type HANDLE
int Param;
if (argc != 2)
{
fprintf(stderr,"An integer parameter is requiredn");
return -1;
}
Param = atoi(argv[1]);
if (Param < 0)
{
fprintf(stderr,"An integer >= 0 is requiredn");
return -1;
}
this code block ensures that the program is provided with the correct number of
command-line arguments which are non-negative integer. If these conditions are not
met, the program prints an error message and exits with a return code of -1, signaling
an error state.
OPERATNG SYSTEM MODULE-2 PRESENTATION OS
• ThreadHandle = CreateThread(...) - creates a
new thread using the CreateThread function
with the parameters passed.
• if (ThreadHandle != NULL) { ... }: This condition
checks if the thread creation was successful by
verifying that ThreadHandle is not NULL. If the
thread was successfully created, the code
inside the if block is executed.
• WaitForSingleObject(ThreadHandle,
INFINITE): waits for the created thread to
finish its execution. The WaitForSingleObject
function suspends the execution of the calling
thread until the specified thread (in this case,
ThreadHandle) terminates.
• INFINITE- wait indefinitely until the thread
finishes.
• CloseHandle(ThreadHandle);: After the
thread has finished, this line closes the handle
to the thread.
• This code creates a thread, waits for it to
finish, closes the thread handle to free up
resources, and then prints the calculated sum
to the console.
Java Threads
• All Java programs comprise at least a single thread
of control—even a simple Java program consisting
of only a main() method runs as a single thread in
the JVM.
• There are two techniques for creating threads in a
Java program.
• One approach is to create a new class that is
derived from the Thread class and to override its
run() method.
• Another approach—and more commonly used—
technique is to define a class that implements the
Runnable interface.
• The Runnable interface is defined as follows:
public interface Runnable
{
public abstract void run();
}
• When a class implements Runnable, it must
define a run() method.
• The code implementing the run() method is
what runs as a separate thread
OPERATNG SYSTEM MODULE-2 PRESENTATION OS
OPERATNG SYSTEM MODULE-2 PRESENTATION OS
– private int sum;: declares a private integer variable named sum.
Private keyword indicates that this variable can only be accessed
within the same class (Sum), and not from outside.
• Getsum Method:
public int getSum()
{
return sum;
}
This method is a getter method, which provides access to the
private sum variable.
It allows other classes to retrieve the value of sum without
directly accessing the variable.
The public keyword means that this method can be called from
outside the class.
• getSum() is used to retrieve the value of the private
sum variable, and the value can be modified using a
corresponding setSum() method.
• public void setSum(int sum) declares a method
named setSum that takes an integer parameter
named sum.
• The method has a void return type, indicating that it
doesn't return any value.
• this.sum = sum assigns the value of the parameter
sum to the private variable sum of the class.
• The use of this.sum is necessary to distinguish
between the class's private variable sum and the
method's parameter sum.
class Summation implements Runnable
The Summation class implements the Runnable
interface, which means instances of this class
can be executed by a separate thread.
private int upper represents the upper limit for
the summation.
It is a private instance variable, meaning it can
only be accessed within the Summation class.
private Sum sumValue variable is of type Sum
and represents an instance of the Sum class. It is
also a private instance variable.
• When the summation program runs, the JVM
creates two threads. The first is the parent
thread, which starts execution in the main()
method.
• The second thread is created when the start()
method on the Thread object is invoked. This
child thread begins execution in the run()
method of the Summation class.
• After outputting the value of the summation,
this thread terminates when it exits from its
run() method.
Ad

More Related Content

Similar to OPERATNG SYSTEM MODULE-2 PRESENTATION OS (20)

Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
Rakesh Madugula
 
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
ssuserfcae42
 
Parallel and Distributed Computing Chapter 5
Parallel and Distributed Computing Chapter 5Parallel and Distributed Computing Chapter 5
Parallel and Distributed Computing Chapter 5
AbdullahMunir32
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Maulik Borsaniya
 
Threading
ThreadingThreading
Threading
abhay singh
 
Threads
ThreadsThreads
Threads
saanchi85
 
Multithreading
MultithreadingMultithreading
Multithreading
backdoor
 
Programming using Open Mp
Programming using Open MpProgramming using Open Mp
Programming using Open Mp
Anshul Sharma
 
An eternal question of timing
An eternal question of timingAn eternal question of timing
An eternal question of timing
PVS-Studio
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
raksharao
 
Generators & Decorators.pptx
Generators & Decorators.pptxGenerators & Decorators.pptx
Generators & Decorators.pptx
IrfanShaik98
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
Muhammad Alhalaby
 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
Mahmoud Ouf
 
25-MPI-OpenMP.pptx
25-MPI-OpenMP.pptx25-MPI-OpenMP.pptx
25-MPI-OpenMP.pptx
GopalPatidar13
 
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbjava.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
jakjak36
 
Java Multithreading - how to create threads
Java Multithreading - how to create threadsJava Multithreading - how to create threads
Java Multithreading - how to create threads
ManishKumar475693
 
MULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptxMULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptx
SaiDhanushM
 
Parallel program design
Parallel program designParallel program design
Parallel program design
ZongYing Lyu
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
ssuserfcae42
 
Parallel and Distributed Computing Chapter 5
Parallel and Distributed Computing Chapter 5Parallel and Distributed Computing Chapter 5
Parallel and Distributed Computing Chapter 5
AbdullahMunir32
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Maulik Borsaniya
 
Multithreading
MultithreadingMultithreading
Multithreading
backdoor
 
Programming using Open Mp
Programming using Open MpProgramming using Open Mp
Programming using Open Mp
Anshul Sharma
 
An eternal question of timing
An eternal question of timingAn eternal question of timing
An eternal question of timing
PVS-Studio
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
raksharao
 
Generators & Decorators.pptx
Generators & Decorators.pptxGenerators & Decorators.pptx
Generators & Decorators.pptx
IrfanShaik98
 
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbjava.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
jakjak36
 
Java Multithreading - how to create threads
Java Multithreading - how to create threadsJava Multithreading - how to create threads
Java Multithreading - how to create threads
ManishKumar475693
 
MULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptxMULTI-THREADING in python appalication.pptx
MULTI-THREADING in python appalication.pptx
SaiDhanushM
 
Parallel program design
Parallel program designParallel program design
Parallel program design
ZongYing Lyu
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 

Recently uploaded (20)

U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
Ad

OPERATNG SYSTEM MODULE-2 PRESENTATION OS

  • 2. • A thread library provides the programmer with an API for creating and managing threads. • There are two primary ways of implementing a thread library. • First approach – is to provide a library entirely in user space with no kernel support. – All code and data structures for the library exist in user space which means that invoking a function in the library results in a local function call in user space and not a system call. • Second approach – is to implement a kernel-level library supported directly by the operating system. – In this case, code and data structures for the library exist in kernel space.
  • 3. • Three main thread libraries are in use today:  POSIX Pthreads  Windows Threads  Java Threads  Two general strategies for creating multiple threads:  Asynchronous threading  Synchronous threading  In asynchronous threading, once the parent creates a child thread, the parent resumes its execution, so that the parent and child execute concurrently.  Each thread runs independently of every other thread, and the parent thread need not know when its child terminates.  Because the threads are independent, there is typically little data sharing between threads.
  • 4. • Synchronous threading occurs when the parent thread creates one or more children and then must wait for all of its children to terminate before it resumes —the so-called fork-join strategy. • Once each thread has finished its work, it terminates and joins with its parent. Only after all of the children have joined , the parent resume execution. • Synchronous threading involves significant data sharing among threads. • For example, the parent thread may combine the results calculated by its various children.
  • 5. • The C program demonstrates the basic Pthreads API for constructing a multithreaded program that calculates the summation of a non-negative integer in a separate thread. • If N is 5, this function would represent the summation of integers from 0 to 5, which is 15
  • 7. #include <pthread.h> #include <stdio.h> int sum; /* This data is shared by the thread(s) */ void *runner(void *param); /* Threads call this function */ int main(int argc, char *argv[]) { pthread_t tid; /* The thread identifier */ pthread_attr_t attr; /* Set of thread attributes */ if (argc != 2) { fprintf(stderr, "usage: %s <integer value>n", argv[0]); return -1; } if (atoi(argv[1]) < 0) { fprintf(stderr, "%d must be >= 0n", atoi(argv[1])); return -1; } /* Get the default attributes */ pthread_attr_init(&attr); /* Create the thread */ pthread_create(&tid, &attr, runner, argv[1]); /* Wait for the thread to exit */ pthread_join(tid, NULL); printf("sum = %dn", sum); return 0; } /* The thread will begin control in this function */ void *runner(void *param) { int i, upper = atoi(param); sum = 0; for (i = 1; i <= upper; i++) sum += i; pthread_exit(0); }
  • 8. • All Pthreads programs must include the pthread.h header file • When creating a new thread, we typically specify a function that the thread will run. This function is sometimes referred to as the "runner function" or "thread function.“ • When this program begins, a single thread of control begins in main(). • After some initialization, main() creates a second thread that begins control in the runner() function. • Both threads share the global data sum. • pthread_t tid : Declares a variable tid of type pthread_t, which is used to identify a thread. • pthread_attr_t attr : Declares a variable attr of type pthread_attr_t, which is used to store thread attributes.
  • 9. if (argc != 2) { fprintf(stderr, "usage: %s <integer value>n", argv[0]); return -1; } if (atoi(argv[1]) < 0) { fprintf(stderr, "%d must be >= 0n", atoi(argv[1])); return -1; } this code block ensures that the program is provided with the correct number of command-line arguments which are non-negative integer. If these conditions are not met, the program prints an error message and exits with a return code of -1, signaling an error state.
  • 10. • A separate thread is created with the pthread create() function call • In addition to passing the thread identifier and the attributes for the thread, we also pass the name of the function where the new thread will begin execution—in this case, the runner() function. • Last, we pass the integer parameter that was provided on the command line, argv[1]. • At this point, the program has two threads: – the initial (or parent) thread in main() – the summation (or child) thread performing the summation operation in the runner() function.
  • 11. • pthread_join() Parent thread waits for the created thread to finish before proceeding with the main thread. • printf("sum = %dn", sum): Prints the calculated sum after the thread has finished. • The summation thread will terminate when it calls the function pthread exit(). • Once the summation thread has returned, the parent thread will output the value of the shared data sum.
  • 12. • Parent Thread (Main Thread): – Initialize Attributes: pthread_attr_init(&attr); – Create Thread: pthread_create(&tid, &attr, runner, argv[1]); – Wait for Thread to Finish: pthread_join(tid, NULL); – Print Result: printf("sum = %dn", sum); • Child Thread (runner function): – Calculate Sum: for (i = 1; i <= upper; i++) sum += i; – Exit Thread: pthread_exit(0);
  • 13. A simple method for waiting on several threads using the pthread join() function is to enclose the operation within a simple for loop.
  • 14. Windows Threads • The technique for creating threads using the Windows thread library is similar to the Pthreads technique in several ways.
  • 16. • The program defines a global variable Sum to store the sum of integers calculated by the thread(s). • The Summation function is the entry point for the thread. • It takes a parameter Param (a pointer to an integer) and calculates the sum of integers from 1 to the value pointed to by Param.
  • 17. DWORD WINAPI Summation(LPVOID Param) /* LPVOID is a generic pointer that indicates that the pointer can point to data of any type */ { DWORD Upper = *(DWORD*)Param; /*retrieves that value from the memory location pointed to by Param and storing it in the variable Upper */ for (DWORD i = 0; i <= Upper; i++) Sum += i; return 0; }
  • 18. int main(int argc, char *argv[]) { DWORD ThreadId; HANDLE ThreadHandle; declares a variable named ThreadHandle of type HANDLE int Param; if (argc != 2) { fprintf(stderr,"An integer parameter is requiredn"); return -1; } Param = atoi(argv[1]); if (Param < 0) { fprintf(stderr,"An integer >= 0 is requiredn"); return -1; } this code block ensures that the program is provided with the correct number of command-line arguments which are non-negative integer. If these conditions are not met, the program prints an error message and exits with a return code of -1, signaling an error state.
  • 20. • ThreadHandle = CreateThread(...) - creates a new thread using the CreateThread function with the parameters passed. • if (ThreadHandle != NULL) { ... }: This condition checks if the thread creation was successful by verifying that ThreadHandle is not NULL. If the thread was successfully created, the code inside the if block is executed.
  • 21. • WaitForSingleObject(ThreadHandle, INFINITE): waits for the created thread to finish its execution. The WaitForSingleObject function suspends the execution of the calling thread until the specified thread (in this case, ThreadHandle) terminates. • INFINITE- wait indefinitely until the thread finishes. • CloseHandle(ThreadHandle);: After the thread has finished, this line closes the handle to the thread.
  • 22. • This code creates a thread, waits for it to finish, closes the thread handle to free up resources, and then prints the calculated sum to the console.
  • 23. Java Threads • All Java programs comprise at least a single thread of control—even a simple Java program consisting of only a main() method runs as a single thread in the JVM. • There are two techniques for creating threads in a Java program. • One approach is to create a new class that is derived from the Thread class and to override its run() method. • Another approach—and more commonly used— technique is to define a class that implements the Runnable interface.
  • 24. • The Runnable interface is defined as follows: public interface Runnable { public abstract void run(); } • When a class implements Runnable, it must define a run() method. • The code implementing the run() method is what runs as a separate thread
  • 27. – private int sum;: declares a private integer variable named sum. Private keyword indicates that this variable can only be accessed within the same class (Sum), and not from outside. • Getsum Method: public int getSum() { return sum; } This method is a getter method, which provides access to the private sum variable. It allows other classes to retrieve the value of sum without directly accessing the variable. The public keyword means that this method can be called from outside the class.
  • 28. • getSum() is used to retrieve the value of the private sum variable, and the value can be modified using a corresponding setSum() method. • public void setSum(int sum) declares a method named setSum that takes an integer parameter named sum. • The method has a void return type, indicating that it doesn't return any value. • this.sum = sum assigns the value of the parameter sum to the private variable sum of the class. • The use of this.sum is necessary to distinguish between the class's private variable sum and the method's parameter sum.
  • 29. class Summation implements Runnable The Summation class implements the Runnable interface, which means instances of this class can be executed by a separate thread. private int upper represents the upper limit for the summation. It is a private instance variable, meaning it can only be accessed within the Summation class. private Sum sumValue variable is of type Sum and represents an instance of the Sum class. It is also a private instance variable.
  • 30. • When the summation program runs, the JVM creates two threads. The first is the parent thread, which starts execution in the main() method. • The second thread is created when the start() method on the Thread object is invoked. This child thread begins execution in the run() method of the Summation class. • After outputting the value of the summation, this thread terminates when it exits from its run() method.
  翻译: