37
Threads Prof. Mrs. Trupti S. Indi Walchand Institute of Technology Department of Information Technology Solapur University

Principle Of Operating System Chapter 3

Embed Size (px)

DESCRIPTION

Principle Of Operating System Chapter 3,Thread Creation,Thread Concept,Thread Concept,Thread Program

Citation preview

Page 1: Principle Of Operating System Chapter 3

Threads

Prof. Mrs. Trupti S. IndiWalchand Institute of TechnologyDepartment of Information TechnologySolapur University

Page 2: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

2

THREADS

• Overview• Multithreading Models• Threading Issues• Pthreads• Windows XP Threads• Linux Threads• Java Threads

Page 3: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

3

Single and Multithreaded Processes

Page 4: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

4

Benefits• Responsiveness: even if part of program is blocked or

performing lengthy operation multithreading allow a program to continue.

• Resource Sharing: threads share the memory & resources of the process within the same address space.

• Economy: Allocating memory & resources for process creation is costly. Threads share resources of the process to which it belongs. Create and context switch threads is more economical.

• Utilization of MP Architectures: In multiprocessor system, each thread running in parallel on a different processor.

Page 5: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

5

User Threads

• Thread management done by user-level threads library

• Three primary thread libraries:– POSIX Pthreads– Win32 threads– Java threads

Page 6: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

6

Kernel Threads

• Supported by the Kernel

• Examples– Windows XP/2000– Solaris– Linux– Tru64 UNIX– Mac OS X

Page 7: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

7

User Threads Vs Kernel Threads

• Support – above kernel or directly by OS

• Space: user space or kernel space

• Thread creation & management – OS or thread

library at user level

• Speed – creation & management

• Drawback:

– Overhead

– If thread performs blocking system call

Page 8: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

8

Multithreading Models

• Many-to-One

• One-to-One

• Many-to-Many

Page 9: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

9

Many-to-One

• Many user-level threads mapped to single kernel

thread

• Thread management in user space (efficient)

• Blocking system call – entire process block

• Parallel execution of threads not possible in this model

• Examples:

– Solaris Green Threads

– GNU Portable Threads

Page 10: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

10

Many-to-One Model

Page 11: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

11

One-to-One

• Each user-level thread maps to kernel thread

• Blocking system call doesn’t block whole process

• More concurrency compared to M:1 model

• Drawback: overhead in creation kernel threads

• Examples

– Windows NT/XP/2000

– Linux

– Solaris 9 and later

Page 12: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

12

One-to-one Model

Page 13: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

13

Many-to-Many Model• Allows many user-level threads to be mapped to many kernel

threads

• Allows the operating system to create a sufficient number of kernel threads

• Blocking system call: kernel reschedule another thread for execution

• More concurrency

Examples:– Solaris prior to version 9– Windows NT/2000 with the ThreadFiber package

Page 14: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

14

Many-to-Many Model

Page 15: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

15

Threading Issues

• Semantics of fork() and exec() system calls

• Thread cancellation

• Signal handling

• Thread pools

• Thread specific data

• Scheduler activations

Page 16: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

16

Semantics of fork() and exec()

• Does fork() duplicate only the calling thread or all threads?

Page 17: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

17

Thread Cancellation• Terminating a thread before it has finished

• Two general approaches:– Asynchronous cancellation terminates the

target thread immediately

– Deferred cancellation allows the target thread to periodically check if it should be cancelled

Page 18: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

18

Signal Handling• Signals are used in UNIX systems to notify a process that

a particular event has occurred

• A signal handler is used to process signals1. Signal is generated by particular event2. Signal is delivered to a process3. Signal is handled

• Options:– Deliver the signal to the thread to which the signal applies– Deliver the signal to every thread in the process– Deliver the signal to certain threads in the process– Assign a specific threa to receive all signals for the process

Page 19: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

19

Thread Pools• Create a number of threads in a pool where

they await work

• Advantages:– Usually slightly faster to service a request with

an existing thread than create a new thread– Allows the number of threads in the

application(s) to be bound to the size of the pool

Page 20: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

20

Thread Specific Data• Allows each thread to have its own copy

of data

• Useful when you do not have control over the thread creation process (i.e., when using a thread pool)

Page 21: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

21

Scheduler Activations• Both M:M require communication to

maintain the appropriate number of kernel threads allocated to the application

• Scheduler activations provide upcalls - a communication mechanism from the kernel to the thread library

• This communication allows an application to maintain the correct number kernel threads

Page 22: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

22

Pthreads• A POSIX standard (IEEE 1003.1c) API for

thread creation and synchronization

• API specifies behavior of the thread library, implementation is up to development of the library

• Common in UNIX operating systems (Solaris, Linux, Mac OS X)

Page 23: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

23

LAB WORKAssignment#4: Write a program to implement multithreaded program using

(a) pthread API(b) java Thread class

Use: man pthread.h

Command: $ cc -pThread program.c -o prgram.out

Study following function1)pthread_create()2)Pthread_join()3)Pthread_exit()

Study command “ps” to list thread information:$ ps -elf

Page 24: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

24

NAMEpthread_create - thread creation

SYNOPSIS #include <pthread.h>

int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr,void *(*start_routine)(void*), void *restrict arg);

DESCRIPTION• The pthread_create() function shall create a new thread, with

attributes specified by attr, within a process. • If attr is NULL, the default attributes shall be used. • If the attributes specified by attr are modified later, the thread's attributes

shall not be affected. • Upon successful completion, pthread_create() shall store the ID of the

created thread in the location referenced by thread.

RETURN VALUEIf successful, the pthread_create() function shall return zero; otherwise, an error number shall be returned to indicate the error.

Page 25: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

25

NAMEpthread_join - wait for thread termination

SYNOPSIS #include <pthread.h> int pthread_join(pthread_t thread, void **value_ptr);

DESCRIPTION• The pthread_join() function shall suspend execution of the calling thread

until the target thread terminates, unless the target thread has already terminated.

• On return from a successful pthread_join() call with a non-NULL value_ptr argument, the value passed to pthread_exit() by the terminating thread shall be made available in the location referenced by value_ptr.

• When a pthread_join() returns successfully, the target thread has been terminated. The results of multiple simultaneous calls to pthread_join() specifying the same target thread are undefined.

• If the thread calling pthread_join() is canceled, then the target thread shall not be detached.

RETURN VALUEIf successful, the pthread_join() function shall return zero; otherwise, an error number shall be returned to indicate the error.

Page 26: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

26

NAMEpthread_exit - thread termination

SYNOPSIS #include <pthread.h> void pthread_exit(void *value_ptr);

DESCRIPTION• The pthread_exit() function shall terminate the calling thread and make the

value value_ptr available to any successful join with the terminating thread.• Any cancellation cleanup handlers that have been pushed and not yet

popped shall be popped in the reverse order that they were pushed and then executed.

• After all cancellation cleanup handlers have been executed, if the thread has any thread-specific data, appropriate destructor functions shall be called in an unspecified order.

• Thread termination does not release any application visible process resources, including, but not limited to, mutexes and file descriptors, nor does it perform any process-level cleanup actions, including, but not limited to, calling any atexit() routines that may exist.

• An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it. The function's return value shall serve as the thread's exit status.

Page 27: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

27

/*Multithreaded C program using the Pthread API*/#include<stdio.h>#include<pthread.h>

#define MAX_THREAD 10

int sum; /* this data is shared by the thread(s)*/void * runner(void *param);

main(int argc, char* argv[]){ pthread_t tid; /* the thread identifier */ pthread_attr_t attr; /* set of thread attributes */ int n;

if (argc != 2) { printf ("Usage: %s n\n where n is no. of threads\n",argv[0]); exit(1); }

Page 28: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

28

/*create the thread*/pthread_create(&tid, &attr, runner, argv[1]);

/*now wait for thread to exit*/pthread_join(tid,NULL);printf("sum = %d\n",sum);

}//end of main

/* The thread will begin control in this function*/void *runner(void *param){ int upper = atoi(param); int i; sum = 0; if(upper>0) { for(i=1; i<=upper; i++) sum += i; } pthread_exit(0);}

Page 29: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

29

/*Program 2: Pthread creation*/#include<stdio.h>#include<sys/types.h>#include<pthread.h>#include<unistd.h>#define MAX_THREAD 1000

typedef struct { int id;} parm;void *hello(void *arg){ parm *p=(parm *)arg; printf("Hello from node %d\n", p->id); return (NULL);}

void main(int argc, char* argv[]) { int n,i;//thread identifierpthread_t *threads;

//set of thread attributespthread_attr_t pthread_custom_attr;

parm *p;

if (argc != 2){printf ("Usage: %s n\n where n is no. of

threads\n",argv[0]);exit(1);}

Page 30: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

30

n=atoi(argv[1]);if ((n < 1) || (n > MAX_THREAD)){printf ("The no of thread should

between 1 and %d.\n",MAX_THREAD);

exit(1);}threads=(pthread_t

*)malloc(n*sizeof(*threads));

pthread_attr_init(&pthread_custom_attr);

p=(parm *)malloc(sizeof(parm)*n);

/* Start up thread */for (i=0; i<n; i++){p[i].id=i;/*create the thread*/pthread_create(&threads[i], &pthread_custom_attr, hello, (void *)(p+i));

}

/* Synchronize the completion of each thread. */

for (i=0; i<n; i++){pthread_join(threads[i],NULL);}free(p);}

Page 31: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

31

Windows XP Threads• Implements the one-to-one mapping

• Each thread contains– A thread id– Register set– Separate user and kernel stacks– Private data storage area

• The register set, stacks, and private storage area are known as the context of the threads

• The primary data structures of a thread include:– ETHREAD (executive thread block)– KTHREAD (kernel thread block)– TEB (thread environment block)

Page 32: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

32

Linux Threads• Linux refers to them as tasks rather than threads

• Thread creation is done through clone() system call

• clone() allows a child task to share the address space of the parent task (process)

Page 33: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

33

Java Threads• Java threads are managed by the JVM

• Java threads may be created by:– Extending Thread class– Implementing the Runnable interface

Page 34: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

34

Java Thread States

Page 35: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

35

/*Multithreaded Java program using the Thread Class*/class Summation extends Thread{

private int upper;public Summation(int n) //Constructor{

upper = n;}public void run(){

int sum = 0;

if(upper > 0){for(int i=1; i<=upper; i++){sum += i;}}System.out.println("\n The sum of "+upper+"is "+sum);

}//end of run

}//end of Summation Class

Page 36: Principle Of Operating System Chapter 3

Prof. T. S. Indi, Walchand Institute of Technology, Solapur University

36

public class ThreadTester{public static void main(String[] args){

if(args.length > 0){if(Integer.parseInt(args[0]) < 0)System.out.println(args[0]+" must be >= 0.");else{Summation thrd = new Summation(Integer.parseInt(args[0]));thrd.start();}}elseSystem.out.println("Usage: Summation <integer value>");}}//end of main

}//end of class ThreadTester

Page 37: Principle Of Operating System Chapter 3

End of Unit 2