Threads By Dr. Yingwu Zhu. Review Multithreading Models Many-to-one One-to-one Many-to-many.

Slides:



Advertisements
Similar presentations
Threads. Readings r Silberschatz et al : Chapter 4.
Advertisements

Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Lecture 6: Threads Chapter 4.
1 Chapter 5 Threads 2 Contents  Overview  Benefits  User and Kernel Threads  Multithreading Models  Solaris 2 Threads  Java Threads.
Threads By Dr. Yingwu Zhu.
Silberschatz, Galvin, and Gagne  Applied Operating System Concepts Module 5: Threads 9/29/03+ Overview Benefits User and Kernel Threads Multithreading.
Fork Fork is used to create a child process. Most network servers under Unix are written this way Concurrent server: parent accepts the connection, forks.
Threads 1 CS502 Spring 2006 Threads CS-502 Spring 2006.
Pthreads Operating Systems Hebrew University of Jerusalem Spring 2004.
Unix Threads operating systems. User Thread Packages pthread package mach c-threads Sun Solaris3 UI threads Kernel Threads Windows NT, XP operating systems.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
02/02/2004CSCI 315 Operating Systems Design1 Threads Notice: The slides for this lecture have been largely based on those accompanying the textbook Operating.
Chapter 4: Threads Adapted to COP4610 by Robert van Engelen.
Chapter 4 Threads. 4.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7 th edition, Jan 23, 2005 Chapter 4: Threads Overview Multithreading.
Thread. A basic unit of CPU utilization. It comprises a thread ID, a program counter, a register set, and a stack. It is a single sequential flow of control.
Operating Systems Chapter 5 Threads. Benefits Responsiveness Resource Sharing Economy Utilization of MP Architectures.
Multithreading Allows application to split itself into multiple “threads” of execution (“threads of execution”). OS support for creating threads, terminating.
Chapter 4: Threads. 4.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts Threads A thread (or lightweight process) is a basic unit of CPU.
10/16/ Realizing Concurrency using the thread model B. Ramamurthy.
Processes and Threads CS550 Operating Systems. Processes and Threads These exist only at execution time They have fast state changes -> in memory and.
B. RAMAMURTHY 10/24/ Realizing Concurrency using the thread model.
Operating Systems CMPSC 473 Multi-threading models Tutorial on pthreads Lecture 10: September Instructor: Bhuvan Urgaonkar.
CS 346 – Chapter 4 Threads –How they differ from processes –Definition, purpose Threads of the same process share: code, data, open files –Types –Support.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
Share Memory Program Example int array_size=1000 int global_array[array_size] main(argc, argv) { int nprocs=4; m_set_procs(nprocs); /* prepare to launch.
Source: Operating System Concepts by Silberschatz, Galvin and Gagne.
CS333 Intro to Operating Systems Jonathan Walpole.
Chapter 4: Threads. 2 Overview Multithreading Models Threading Issues Pthreads Windows XP Threads Linux Threads.
Pthreads: A shared memory programming model
Threads CSCE Thread Motivation Processes are expensive to create. Context switch between processes is expensive Communication between processes.
Pthreads.
Shan Gao Fall 2007 Department of Computer Science Georgia State University.
Multithreaded Programing. Outline Overview of threads Threads Multithreaded Models  Many-to-One  One-to-One  Many-to-Many Thread Libraries  Pthread.
Silberschatz, Galvin and Gagne  2002 Modified for CSCI 399, Royden, Operating System Concepts Operating Systems Lecture 14 Threads 2 Read Ch.
Chapter 4: Threads. 4.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7 th edition, Jan 23, 2005 Outline n Overview n Multithreading.
12/22/ Thread Model for Realizing Concurrency B. Ramamurthy.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Operating Systems Processes and Threads.
CS307 Operating Systems Threads Fan Wu Department of Computer Science and Engineering Shanghai Jiao Tong University Spring 2011.
Threads Dr. Yingwu Zhu. Threaded Applications Web browsers: display and data retrieval Web servers Many others.
CSC 360, Instructor: Kui Wu Thread & PThread. CSC 360, Instructor: Kui Wu Agenda 1.What is thread? 2.User vs kernel threads 3.Thread models 4.Thread issues.
Copyright ©: Nahrstedt, Angrave, Abdelzaher
Threads A thread is an alternative model of program execution
Threads. Thread A basic unit of CPU utilization. An Abstract data type representing an independent flow of control within a process A traditional (or.
Operating System Concepts
CSS430 Threads1 Textbook Ch5 These slides were compiled from the OSC textbook slides (Silberschatz, Galvin, and Gagne) and the instructor’s class materials.
CISC2200 Threads Fall 09. Process  We learn the concept of process  A program in execution  A process owns some resources  A process executes a program.
B. RAMAMURTHY 5/10/2013 Amrita-UB-MSES Realizing Concurrency using the thread model.
7/9/ Realizing Concurrency using Posix Threads (pthreads) B. Ramamurthy.
CMSC 421 Spring 2004 Section 0202 Part II: Process Management Chapter 5 Threads.
1 Chapter 5: Threads Overview Multithreading Models & Issues Read Chapter 5 pages
Tutorial 4. In this tutorial session we’ll see Threads.
A thread is a basic unit of CPU utilization within a process Each thread has its own – thread ID – program counter – register set – stack It shares the.
Realizing Concurrency using the thread model
Threads Some of these slides were originally made by Dr. Roger deBry. They include text, figures, and information from this class’s textbook, Operating.
Lesson One – Creating a thread
Realizing Concurrency using the thread model
Threads in C Caryl Rahn.
CS399 New Beginnings Jonathan Walpole.
Thread Programming.
Chapter 4: Threads.
Realizing Concurrency using Posix Threads (pthreads)
Operating Systems Lecture 13.
Realizing Concurrency using the thread model
Realizing Concurrency using the thread model
Operating System Concepts
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
Tutorial 4.
Outline Chapter 3: Processes Chapter 4: Threads So far - Next -
Presentation transcript:

Threads By Dr. Yingwu Zhu

Review Multithreading Models Many-to-one One-to-one Many-to-many

Many-to-one Model Kernels do not support multiple threads of control Multithreading can be implemented entirely as a user-level library Schedule multiple threads onto the process’s single kernel thread; multiplexing multiple user threads on a single kernel thread

Many-to-one (cont.): Benefits Cheap synchronization When a user thread wishes to perform synchronization, the user-level thread lib. checks to see if the thread needs to block. If a user thread does, the user-level thread lib. enqueues it, and dequeues another user thread from the lib.’s run queue, and swithes the active thread. No system calls are required Cheap thread creation The thread lib. need only create a context (i.e., a stack and registers) and enqueues it in the user-level run queue

Many-to-one (cont.): Benefits Resource efficiency Kernel memory is not wasted on a stack for each user thread Allows as many thread as VM permits Portability User-level threads packages are implemented entirely with standard UNIX and POSIX lib. calls

Many-to-one (cont.): Drawbacks Single-threaded OS interface If a user thread blocks (e.g, blocking system calls), the entire process blocks and so no other user thread can execute until the kernel thread (which is blocked in the system call) becomes available Solution: using nonblocking system calls Can not utilize MP achitectures Examples: Java, Netscape

One-to-one Model Each user thread has a kernel thread

One-to-one (cont.): Benefits Scalable parallelism Each kernel thread is a different kernel-schedulable entity; multiple threads can run concurrently on multiprocessors Multithreaded OS interface When one user thread and its kernel thread block, the other user threads can continue to execute since their kernel threads are unaffected

One-to-one (cont.): Drawbacks Expensive synchronization Kernel threads require kernel involvement to be scheduled; kernel thread synchronization will require a system call if the lock is not immediately acquired If a trap is required, synchronization will be from 3-10 times more costly than many-to-one model Expensive creation Every thread creation requires explicit kernel involvement and consumes kernel resources 3-10 times more expensive than creating a user thread

One-to-one (cont.): Drawbacks Resource inefficiency Every thread created by the user requires kernel memory for a stack, as well as some sort of kernel data structure to keep track of it Many parts of many kernels cannot be paged out The presence of kernel threads is likely to displace physical memory for applications

Many-to-Many Model Combing the previous two models User threads are multiplexed on top of kernel threads which in turn are scheduled on top of processors Taking advantage of the previous two models while minimizing both’s disadvantages Creating a user thread does not necessarily require the creation of a kernel threads; synchronization can be purely user-level

Pthread Tutorial Creating and destroying threads How to use POSIX threads

How to compile? $ gcc –o proj2 proj2.c –pthread The option specifies that pthreads library should be linked causes the complier to properly handle multiple threads in the code that it generates

Creating and Destroying Threads Creating threads Step 1: create a thread Step 2: send the thread one or more parameters Destroy threads Step 1: destroy a thread Step 2: retrieve one or more values that are returned from the thread

Creating Threads #include int pthread_create (pthread_t *thread_id, pthread_attr_t *attr, void *(*thread_fun)(void *), void *args); - The #1 para returns thread ID - The #2 para pointing to thread attr. NULL represents using the default attr. settings - The #3 para as pointer to a function the thread is to execute - The #4 para is the arguments to the function

Thread Terminates Pthreads terminate when the function returns, or the thread calls pthread_exit() int pthread_exit(void *status); status is the return value of the thread A thread_fun returns a void*, so calling “return (void *) is the equivalent of this function

Thread termination One thread can wait (or block) on the termination of another by using pthread_join() You can collect the exit status of all threads you created by pthread_join() int pthread_join(pthread_t thread_id, void **status) The exit status is returned in status pthread_t pthread_self(); Get its own thread id int pthread_equal(pthread_t t1, pthread_t t2); Compare two thread ids

Example #include void *thread_fun(void *arg) { int *inarg = (int *)arg; … return NULL; } Int main() { pthread_t tid; void *exit_state; int val = 42; pthread_create(&tid, NULL, thread_fun, &value); pthread_join(tid, &exit_state); return 0; }

Kill Threads Kill a thread before it returns normally using pthread_cancel() But Make sure the thread has released any local resources; unlike processes, the OS will not clean up the resources Why? Threads in a process share resources

Exercise Write a multithreaded program that calculates the summation of a non-negative integer in a separate thread The non-negative integer is from command-line parameter The summation result is kept in a global variable: int sum; // shared by threads

Step 1: write a thread function void *thread_sum(void *arg) { int i; int m = (int)(*arg); sum = 0; //initialization for (i = 0; i <= sum; i++) sum += I; pthread_exit(0); }

Step 2: write the main() int sum; int main(int argc, char *argv[]) { pthread_t tid; if (argc != 2) { printf(“Usage: %s \n”, argv[0]); return -1; } int i = atoi(argv[1]); if (i < 0) { printf(“integer para must be non-negative\n”); return -2; } pthread_create(&tid, NULL, thread_sum, &i); pthread_join(tid, NULL); printf(“sum = %d\n”, sum); }

Exercise Write a program that creates 10 threads. Have each thread execute thesame function and pass each thread a unique number. Each thread should print “Hello, World (thread n)” five times where ‘n’ is replaced by the thread’s number. Use an array of pthread t objects to hold the various thread IDs. Be sure the program doesn’t terminate until all the threadsare complete. Try running your program on more than one machine. Are there any differences in how it behaves?

Returning Results from Threads Thread function return a pointer to void: void * Pitfalls in return value

Pitfall #1 void *thread_function ( void *) { int code = DEFAULT_VALUE; return ( void *) code ; } Only work in machines where integers can convert to a point and then back to an integer without loss of information

Pitfall #2 void *thread_function ( void *) { char buffer[64]; // fill up the buffer with sth good return ( void *) buffer; } This buffer will disappear as the thread function returns

Pitfall #3 void *thread_function ( void *) { static char buffer[64]; // fill up the buffer with sth good return ( void *) buffer; } It does not work in the common case of multiple threads running the same thread funciton

Right Way void *thread_function ( void *) { char* buffer = (char *)malloc(64); // fill up the buffer with sth good return ( void *) buffer; }

Right Way int main() { void *exit_state; char *buffer; …. pthread_join(tid, &exit_state); buffer = (char *) exit_state; printf(“from thread %d: %s\n”, tid, buffer); free(exit_state); }

Exercise Write a program that computes the square roots of the integers from 0 to 99 in a separate thread and returns an array of doubles containing the results. In the meantime the main thread should display a short message to the user and then display the results of the computation when they are ready.

Exercise In textbook 4.7 and 4.9