Operating System Lecture Slides By Silberschatz, Galvin & Gagne (8 th Edition) Modified By: Prof. Mitul K. Patel Shree Swami Atmanand Saraswati Institute of Technology, Surat January 2012
Outline 1 Chapter - 4: Threads Overview Multithreading Models Thread Libraries Threading Issues 2 Basic Concepts Scheduling Criteria Scheduling Algorithms
Chapter - 4: Threads Outline of Chapter - 4 Overview Multithreading Models Thread Libraries Threading Issues
Chapter - 4: Threads Objective To introduce the notion of a thread a fundamental unit of CPU utilization that forms the basis of multithreaded computer systems To examine issues related to multithreaded programming
Chapter - 4: Threads Overview Single & Multithreaded Processes
Chapter - 4: Threads Overview Multithreaded Server Architecture
Chapter - 4: Threads Overview Benefits of Multithreading Responsiveness Resource Sharing Economy Scalability
Chapter - 4: Threads Overview Multicore Programming Multicore systems putting pressure on programmers, challenges include Dividing activities Balance Data splitting Data dependency Testing and debugging
Chapter - 4: Threads Overview Concurrent execution on a single core system Vs. Parallel execution on a Multicore System Figure: Single core sequential execution
Chapter - 4: Threads Overview Concurrent execution on a single core system Vs. Parallel execution on a Multicore System Figure: Single core sequential execution Figure: Multicore parallel execution
Chapter - 4: Threads Overview User Threads Thread management done by user-level threads library Three primary thread libraries: POSIX Pthreads Win32 threads Java threads
Chapter - 4: Threads Overview Kernel Threads Supported by the Kernel Examples are 1 Windows XP/2000 2 Solaris 3 LINUX 4 True64 UNIX 5 Mac OS X
Chapter - 4: Threads Multithreading Models Multithreading Models There are different three multithreading models available: Many-to-one One-to-one Many-to-many
Chapter - 4: Threads Multithreading Models Many-to-one Model Many user-level threads mapped to single kernel thread Examples are 1 Solaris Green Threads 2 GNU Portable Threads
Chapter - 4: Threads Multithreading Models Many-to-one Model
Chapter - 4: Threads Multithreading Models One-to-one Model Each user-level thread maps to kernel thread Examples are 1 Windows NT/XP/2000 2 Linux 3 Solaris 9 and later
Chapter - 4: Threads Multithreading Models One-to-one Model
Chapter - 4: Threads Multithreading Models 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 Solaris prior to version 9 Windows NT/2000 with the ThreadFiber package
Chapter - 4: Threads Multithreading Models Many-to-many Model
Chapter - 4: Threads Multithreading Models Two level Model Similar to M:M, except that it allows a user thread to be bound to kernel thread Examples are 1 IRIX 2 HP-UX 3 True64 UNIX 4 Solaris 8 and Earlier
Chapter - 4: Threads Multithreading Models Two level Model
Chapter - 4: Threads Thread Libraries Thread Libraries Thread library provides programmer with API for creating and managing threads Two primary ways of implementing 1 Library entirely in user space 2 Kernel-level library supported by the OS
Chapter - 4: Threads Thread Libraries Pthreads May be provided either as user-level or kernel-level 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)
Chapter - 4: Threads Thread Libraries Win32 Threads Win32 thread is a kernel-level library available on windows system Threads are created in the win32 API using the CreateThread( ) function and a set of attributes for the thread is passed to this function These attributes include security information, the size of stack, and a flag that can be set to indicate if the thread is to start in the suspended state
Chapter - 4: Threads Thread Libraries JAVA Threads Java threads are managed by the JVM Typically implemented using the threads model provided by underlying OS Java threads may be created by: 1 Extending Thread class 2 Implementing the Runnable interface
Chapter - 4: Threads Threading Issues Threading Issues Semantics of fork() and exec() system calls Thread cancelation of target thread Asynchronous or deferred Signal handling Thread pools Thread-specific data Scheduler activations
Chapter - 4: Threads Threading Issues Semantics of fork() and exec() Does fork() duplicate only the calling thread or all threads? UNIX system have two version of fork() One that duplicates all threads and Another that duplicates only the thread that invoked the fork() system call If a thread invokes the exec() system call, the program specified in the parameter to exec() will replace the entire process including all threads
Chapter - 4: Threads Threading Issues Thread Cancelation Terminating a thread before it has finished Two general approaches: 1 Asynchronous cancellation terminates the target thread immediately 2 Deferred cancellation allows the target thread to periodically check if it should be cancelled
Chapter - 4: Threads Threading Issues 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 signals 1 Signal is generated by particular event 2 Signal is delivered to a process 3 Signal is handled In multithreaded program, where should a signal be delivered? The Options are: 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 thread to receive all signals for the process
Chapter - 4: Threads Threading Issues Thread Pools In multithreading web server, whenever the server receives the thread request, it creates the separate thread to service the request The first issue is the amount of time required to create the thread prior to servicing the request, together with the fact that this thread will be discarded once it completes its assigned work Second issue is if we allow all concurrent requests to be serviced in the new thread, we have not placed a bound on the no. of threads concurrently active in the system One solution is to 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
Chapter - 4: Threads Threading Issues 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)
Chapter - 4: Threads Threading Issues Scheduler Activation Both M:M and Two-level models 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
Outline of Chapter - 5 Basic Concepts Scheduling Criteria Scheduling Algorithms Thread Scheduling Multiple-Processor Scheduling Algorithm Evaluation
Objectives To introduce CPU scheduling, which is the basis for multiprogrammed operating systems To describe various CPU-scheduling algorithms To discuss evaluation criteria for selecting a CPU-scheduling algorithm for a particular system
Basic Concepts Basic Concepts Maximum CPU utilization obtained with multiprogramming CPUI/O Burst Cycle Process execution consists of a cycle of CPU execution and I/O wait CPU burst distribution
Basic Concepts Alternating Sequence of CPU And I/O Bursts
Basic Concepts Histogram of CPU-burst Times
Basic Concepts CPU Scheduler Selects from among the processes in memory that are ready to execute, and allocates the CPU to one of them CPU scheduling decisions may take place when a process: 1 Switches from running to waiting state (for e.g., wait for the termination of child or waiting for I/O) 2 Switches from running to ready state (for e.g., when interrupt occurs) 3 Switches from waiting to ready (for e.g., at completion of I/O) 4 Terminates Scheduling under 1 and 4 is non-preemptive or cooperative All other scheduling is preemptive
Basic Concepts Dispatcher Dispatcher module gives control of the CPU to the process selected by the short-term scheduler; this involves: switching context switching to user mode jumping to the proper location in the user program to restart that program Dispatch latency time it takes for the dispatcher to stop one process and start another running
Scheduling Criteria Scheduling Criteria CPU utilization keep the CPU as busy as possible Throughput per time unit No. of processes that complete their execution Turnaround time The interval from the time of submission of a process to the time of completion. Turnaround time is the sum of the periods spent waiting to get into memory, waiting in the ready queue, executing on the CPU, and doing I/O Waiting time sum of the periods a process spent waiting in the ready queue Response time amount of time it takes from when a request was submitted until the first response is produced, not output (for time-sharing environment)
Scheduling Criteria Scheduling Algorithm Optimization Criteria CPU utilization -
Scheduling Criteria Scheduling Algorithm Optimization Criteria CPU utilization - Max Throughput -
Scheduling Criteria Scheduling Algorithm Optimization Criteria CPU utilization - Max Throughput - Max Turnaround time -
Scheduling Criteria Scheduling Algorithm Optimization Criteria CPU utilization - Max Throughput - Max Turnaround time - Min Waiting time -
Scheduling Criteria Scheduling Algorithm Optimization Criteria CPU utilization - Max Throughput - Max Turnaround time - Min Waiting time - Min Response time -
Scheduling Criteria Scheduling Algorithm Optimization Criteria CPU utilization - Max Throughput - Max Turnaround time - Min Waiting time - Min Response time - Min
Scheduling Algorithms First-Come, First-Served (FCFS) Scheduling Process Burst Time P 1 24 P 2 3 P 3 3 Suppose that the processes arrive in the order: P 1, P 2, P 3. The Gantt Chart for the schedule is: Waiting time for P 1 = 0; P 2 = 24; P 3 = 27 Average waiting time: (0 + 24 + 27)/3 = 17
Scheduling Algorithms FCFS Scheduling (Con t) Suppose that the processes arrive in the order P 2, P 3, P 1 The Gantt chart for the schedule is: Waiting time for P 1 = 6; P 2 = 0; P 3 = 3 Average waiting time: (6 + 0 + 3)/3 = 3 Much better than previous case Convoy effect - short process behind long process FCFS scheduling algorithm is non-preemptive FCFS algorithm is troublesome for time-sharing systems as in time sharing system, every process should get the equal chance to get into the CPU
Scheduling Algorithms Shortest Job First Scheduling Associate with each process the length of its next CPU burst. Use these lengths to schedule the process with the shortest time SJF is optimal gives minimum average waiting time for a given set of processes The difficulty is knowing the length of the next CPU request
Scheduling Algorithms Example of SJF Process Arrival Time Burst Time P 1 0.0 6 P 2 2.0 8 P 3 4.0 7 P 4 0.0 3 SJF Scheduling Chart Average waiting time = (3 + 16 + 9 + 0) / 4 = 7
Scheduling Algorithms Determining Length of Next CPU Burst Can only estimate the length Can be done by using the length of previous CPU bursts, using exponential averaging 1 t n = actual length of n th CPU Burst 2 τ n+1 = predicted value for the next CPU Burst 3 α, 0 α 1 4 Define: τ n+1 = αt n + (1 α)τ n
Scheduling Algorithms Examples of Exponential Averaging α = 0 τ n+1 = τ n Recent history does not count α = 1 τ n+1 = αt n Only the actual last CPU burst counts If we expand the formula, we get: τ n+1 = αt n + (1 α)αt n 1 +... + (1 α) j αt n j +... + (1 α) n+1 τ 0 Since both α and (1 α) are less than or equal to 1, each successive term has less weight than its predecessor
Scheduling Algorithms Prediction of the Length of the Next CPU Burst
Scheduling Algorithms Shortest Remaining Time First Scheduling (Preemptive SJF Scheduling) Process Arrival Time Burst Time P 1 0 8 P 2 1 4 P 3 2 9 P 4 3 5 SJF Scheduling Chart Average waiting time = [(10 1) + (1 1) + (17 2) + (5 3)]/4 = 26/4 = 6.5 Non-preemptive scheduling would result in an average waiting time of 7.75 milliseconds
Scheduling Algorithms Priority Scheduling A priority number (integer) is associated with each process The CPU is allocated to the process with the highest priority (smallest integer highest priority) Preemptive priority scheduling algorithm will preempt the CPU if the priority of the newly arrived process is higher than the priority of the currently running process Non-preemptive priority scheduling algorithm will simply put the new process at the head of the ready queue SJF is a priority scheduling where priority is the predicted next CPU burst time
Scheduling Algorithms Priority Scheduling Example Process Burst Time Priority P 1 10 3 P 2 1 1 P 3 2 4 P 4 1 5 P 5 5 2 Priority scheduling chart Average waiting time is 8.2 milliseconds. Problem Starvation or indefinite blocking low priority processes may never execute Solution Aging as time progresses increase the priority of the process
Scheduling Algorithms Round Robin Each process gets a small unit of CPU time (time quantum), usually 10-100 milliseconds. After this time has elapsed, the process is preempted and added to the end of the ready queue
Scheduling Algorithms Example of RR with Time Quantum = 4 Process Burst Time P 1 24 P 2 3 P 3 3 The Gantt chart is: The average waiting time is [(10-4)+4+7] / 3 = 17 / 3 = 5.66 milliseconds Typically, higher average turnaround than SJF, but better response
Scheduling Algorithms Round Robin Algorithm Performance If there are n processes in the ready queue and the time quantum is q, then each process gets 1/n of the CPU time in chunks of at most q time units at once. No process waits more than (n-1)q time units. For example, with five processes and the time quantum of 20 milliseconds, each process will get up to 20 milliseconds after every 100 milliseconds Performance Time quantum q large FIFO Time quantum q small q must be large with respect to context switch, otherwise overhead is too high and this RR approach is called processor sharing
Scheduling Algorithms Time Quantum and Context Switch Time The time quantum should be large compared with the context switch time, it should not be too large If the time quantum is too large, then RR scheduling degenerates to an FCFS policy The rule of thumb is that 80 percent of the CPU bursts should be shorter than the time quantum
Scheduling Algorithms Turnaround Time Varies With The Time Quantum
Scheduling Algorithms Multilevel Queue Ready queue is partitioned into separate queues: foreground (interactive) background (batch) Foreground processes may have priority over background processes Each queue has its own scheduling algorithm foreground RR background FCFS Scheduling must be done between the queues Fixed priority scheduling; (i.e., serve all from foreground then from background). Possibility of starvation Time slice each queue gets a certain amount of CPU time which it can schedule amongst its processes; i.e., 80% to foreground in RR 20% to background in FCFS
Scheduling Algorithms Multilevel Queue Scheduling
Scheduling Algorithms Multilevel Feedback Queue A process can move between the various queues; aging can be implemented this way If a process uses too much CPU time, it will be moved to a lower priority queue. This scheme leaves I/O bound and interactive processes in the higher priority queues. In addition, a process that waits too long in lower priority queue may be moved to the higher priority queue. Multilevel-feedback-queue scheduler defined by the following parameters: 1 number of queues 2 scheduling algorithms for each queue 3 method used to determine when to upgrade a process 4 method used to determine when to demote a process 5 method used to determine which queue a process will enter when that process needs service
Scheduling Algorithms Example of Multilevel Feedback Queue Three queues: Q 0 RR with time quantum 8 milliseconds Q 1 RR time quantum 16 milliseconds Q 2 FCFS Scheduling A new job enters queue Q 0 which is served RR. When it gains CPU, job receives 8 milliseconds. If it does not finish in 8 milliseconds, job is moved to queue Q 1. At Q 1 job is again served RR and receives 16 additional milliseconds. If it still does not complete, it is preempted and moved to queue Q 2.
Scheduling Algorithms Multilevel Feedback Queues
Scheduling Algorithms Thread Scheduling Distinction between user-level and kernel-level threads Many-to-one and many-to-many models, thread library schedules user-level threads to run on LWP Known as process-contention scope (PCS) since scheduling competition is between the threads belongs to the same process Kernel thread scheduled onto available CPU is system-contention scope (SCS) competition among all threads in system PCS is done according to the priority scheduler selects the runnable thread with the highest priority to run
Scheduling Algorithms Pthread Scheduling API allows specifying either PCS or SCS during thread creation PTHREAD SCOPE PROCESS schedules threads using PCS scheduling PTHREAD SCOPE SYSTEM schedules threads using SCS scheduling On system implementing many-to-many model, the PTHREAD SCOPE PROCESS policy schedules user-level thread onto available LWPs. The PTHREAD SCOPE SYSTEM scheduling policy will create and bind an LWP for each user-level thread on many-tomany systems, effectively mapping threads using the one-to-one policy.
Scheduling Algorithms Pthread Scheduling API
Scheduling Algorithms Pthread Scheduling API
Scheduling Algorithms Multiprocessor Scheduling CPU scheduling more complex when multiple CPUs are available Homogeneous processors within a multiprocessor Asymmetric multiprocessing only one processor accesses the system data structures, reducing the need for data sharing Symmetric multiprocessing(smp) each processor is selfscheduling, all processes in common ready queue, or each has its own private queue of ready processes Processor affinity process has affinity for processor on which it is currently running 1 soft affinity OS attempts to keep the process running on the same processor but not guaranteeing that it will do so 2 hard affinity Allowing a process to specify that it is not to migrate to other processor
Scheduling Algorithms NUMA and CPU Scheduling
Scheduling Algorithms Load Balancing Load balancing attempts to keep the workload evenly distributed across all processors in SMP systems In most contemporary operating systems supporting SMP, each processor does have a private queue of eligible processes There are two general approaches to load balancing: push migration and pull migration With push migration, a specific task periodically checks the load on each processor and if it finds an imbalance evenly distributes the load by moving the processes from overloaded to idle or less busy processors Pull migration occurs when an idle processor pulls a waiting task from a busy processor
Scheduling Algorithms Multicore Processors Recent trend to place multiple processor cores on same physical chip Faster and consume less power Multiple threads per core also growing Takes advantage of memory stall to make progress on another thread while memory retrieve happens There are two ways to multi thread a processor Course-grained a thread executes on a processor until long latency events such as a memory stall occurs Fine-grained or interleaved multithreading switches between threads at a much finer level of granularity typically at the boundary of an instruction
Scheduling Algorithms Multithreaded Multicore System
Scheduling Algorithms Algorithm Evaluation Criteria to select an algorithm may include several measures such as Maximizing CPU utilization under the constraint that the maximum response time is 1 second Maximizing throughput such that turnaround time is linearly proportional to total execution time There are three different algorithm evaluation methods available Deterministic modeling takes a particular predetermined workload and defines the performance of each algorithm for that workload Queuing models Simulations Implementation
Scheduling Algorithms Deterministic Model In this method, we takes a particular predetermined workload and defines the performance of each algorithm for that workload. As for example: Process Burst Time (ms) P 1 10 P 2 29 P 3 3 P 4 7 P 5 12 Consider the FCFS, SJF, RR with q=10ms In FCFS Average waiting time: P 1, P 2, P 3, P 4, P 5 (0 + 10 + 39 + 42 + 49)/5 = 28ms
Scheduling Algorithms Deterministic Model (con t) With non-preemptive SJF: P 3, P 4, P 1, P 5, P 2 (10 + 32 + 0 + 3 + 20)/5 = 13ms In RR algorithm: P 1, P 2, P 3, P 4, P 5, P 2, P 5, P 2 (0 + 32 + 20 + 23 + 40)/5 = 23ms Conclusion, SJF policy is more efficient This model is simple & fast, gives exact number for comparison
Scheduling Algorithms Queueing Model Rather than computing average waiting time, in this model determine the distribution of CPU and I/O burst. This distribution may be measured and then approximated or simply estimated. By using several mathematical formula, describing the probability of a particular CPU burst. From this approximation, it is possible to compute average throughput, utilization, working time and so on. This area of study is also called queuing-network analysis.
Scheduling Algorithms Queueing Model (Con t) As an example, Let n be the average queue length (excluding process being served) W be the average waiting time in the queue. λ be the average arrival rate for the new processes in the ready queue. If the system is steady state, then number of processes leaving the queue must be equal to the number of processes that arrives, Thus... n = λ W This formula is known as Littles formula.
Scheduling Algorithms Evaluation of CPU schedulers by Simulation