Processes Prof. James L. Frankel Harvard University. Version of 6:16 PM 10-Feb-2017 Copyright 2017, 2015 James L. Frankel. All rights reserved.

Similar documents
Processes The Process Model. Chapter 2. Processes and Threads. Process Termination. Process Creation

Chapter 2 Processes and Threads

Processes The Process Model. Chapter 2 Processes and Threads. Process Termination. Process States (1) Process Hierarchies

Threads. Threads The Thread Model (1) CSCE 351: Operating System Kernels Witawas Srisa-an Chapter 4-5

CS450/550 Operating Systems

PROCESSES & THREADS. Charles Abzug, Ph.D. Department of Computer Science James Madison University Harrisonburg, VA Charles Abzug

CS450/550 Operating Systems

Chapter 2 Processes and Threads. Interprocess Communication Race Conditions

Main Points of the Computer Organization and System Software Module

Review. Preview. Three Level Scheduler. Scheduler. Process behavior. Effective CPU Scheduler is essential. Process Scheduling

System Call. Preview. System Call. System Call. System Call 9/7/2018

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

CSE 153 Design of Operating Systems

What are they? How do we represent them? Scheduling Something smaller than a process? Threads Synchronizing and Communicating Classic IPC problems

Announcements. Reading. Project #1 due in 1 week at 5:00 pm Scheduling Chapter 6 (6 th ed) or Chapter 5 (8 th ed) CMSC 412 S14 (lect 5)

Processes and Non-Preemptive Scheduling. Otto J. Anshus

OS 1 st Exam Name Solution St # (Q1) (19 points) True/False. Circle the appropriate choice (there are no trick questions).

Announcements. Program #1. Program #0. Reading. Is due at 9:00 AM on Thursday. Re-grade requests are due by Monday at 11:59:59 PM.

Operating Systems Comprehensive Exam. Spring Student ID # 3/16/2006

Chapter 2 - Processes and Threads

Process Concepts. CSC400 - Operating Systems. 3. Process Concepts. J. Sumey

Lecture 9: Midterm Review

Operating Systems Comprehensive Exam. Spring Student ID # 3/20/2013

Modern Computers often do lots of things at the same time (web servers, accessing disks, background processes waiting for s,...).

Announcements. Program #1. Reading. Due 2/15 at 5:00 pm. Finish scheduling Process Synchronization: Chapter 6 (8 th Ed) or Chapter 7 (6 th Ed)

Advanced Operating Systems (CS 202) Scheduling (1)

CS510 Operating System Foundations. Jonathan Walpole

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

CSE 153 Design of Operating Systems Fall 2018

Department of Computer applications. [Part I: Medium Answer Type Questions]

8: Scheduling. Scheduling. Mark Handley

SYNCHRONIZATION M O D E R N O P E R A T I N G S Y S T E M S R E A D 2. 3 E X C E P T A N D S P R I N G 2018

Course Syllabus. Operating Systems

Dealing with Issues for Interprocess Communication

CS 326: Operating Systems. CPU Scheduling. Lecture 6

MARUTHI SCHOOL OF BANKING (MSB)

Major Requirements of an OS

CSC Operating Systems Spring Lecture - XII Midterm Review. Tevfik Ko!ar. Louisiana State University. March 4 th, 2008.

OPERATING SYSTEMS. After A.S.Tanenbaum, Modern Operating Systems, 3rd edition. Uses content with permission from Assoc. Prof. Florin Fortis, PhD

UNIT:2. Process Management

Process Scheduling Queues

Timers 1 / 46. Jiffies. Potent and Evil Magic

Q1. State True/false with jusification if the answer is false:

CHAPTER 2: PROCESS MANAGEMENT

Announcement. Exercise #2 will be out today. Due date is next Monday

Subject: Operating System (BTCOC403) Class: S.Y.B.Tech. (Computer Engineering)

Processes and Threads

CSCI-GA Operating Systems Lecture 3: Processes and Threads -Part 2 Scheduling Hubertus Franke

ECE 7650 Scalable and Secure Internet Services and Architecture ---- A Systems Perspective. Part I: Operating system overview: Processes and threads

Unit I. Chapter 2: Process and Threads

Techno India Batanagar Department of Computer Science & Engineering. Model Questions. Multiple Choice Questions:

OPERATING SYSTEMS. COMS W1001 Introduction to Information Science. Boyi Xie

OPERATING SYSTEMS. UNIT II Sections A, B & D. An operating system executes a variety of programs:

Processes and Threads. Processes and Threads. Processes (2) Processes (1)

CHAPTER NO - 1 : Introduction:

Operating Systems Design Fall 2010 Exam 1 Review. Paul Krzyzanowski

SMD149 - Operating Systems

Lecture Topics. Announcements. Today: Uniprocessor Scheduling (Stallings, chapter ) Next: Advanced Scheduling (Stallings, chapter

Learning Outcomes. Processes and Threads. Major Requirements of an Operating System. Processes and Threads

CS3733: Operating Systems

Operating System Concepts Ch. 5: Scheduling

Processes. Overview. Processes. Process Creation. Process Creation fork() Processes. CPU scheduling. Pål Halvorsen 21/9-2005

CS 5523: Operating Systems

Review: Easy Piece 1

Announcements/Reminders

CSE120 Principles of Operating Systems. Prof Yuanyuan (YY) Zhou Scheduling

Process Scheduling. Copyright : University of Illinois CS 241 Staff

2 Processes. 2 Processes. 2 Processes. 2.1 The Process Model. 2.1 The Process Model PROCESSES OPERATING SYSTEMS

Process Description and Control

Today s Topics. u Thread implementation. l Non-preemptive versus preemptive threads. l Kernel vs. user threads

CS 318 Principles of Operating Systems

Mon Sep 17, 2007 Lecture 3: Process Management

CS 3733 Operating Systems

Lecture 2 Process Management

Processes. Sanzheng Qiao. December, Department of Computing and Software

CS 326: Operating Systems. Process Execution. Lecture 5

THE PROCESS ABSTRACTION. CS124 Operating Systems Winter , Lecture 7

Scheduling. Scheduling 1/51

CS-537: Midterm Exam (Spring 2001)

CSE 380 Computer Operating Systems. Instructor: Insup Lee. University of Pennsylvania Fall 2003

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017

Processes, Context Switching, and Scheduling. Kevin Webb Swarthmore College January 30, 2018

CS370 Operating Systems Midterm Review

Last Class: Processes

HY345 - Operating Systems

CISC 7310X. C05: CPU Scheduling. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 3/1/2018 CUNY Brooklyn College

Sample Questions. Amir H. Payberah. Amirkabir University of Technology (Tehran Polytechnic)

What s An OS? Cyclic Executive. Interrupts. Advantages Simple implementation Low overhead Very predictable

Tasks. Task Implementation and management

Precept 2: Non-preemptive Scheduler. COS 318: Fall 2018

Midterm Exam. October 20th, Thursday NSC

Lecture 17: Threads and Scheduling. Thursday, 05 Nov 2009

TDIU25: Operating Systems II. Processes, Threads and Scheduling

Unit 3 : Process Management

Operating Systems. Scheduling

Processes and Threads

Synchronization I. Jo, Heeseung

Processes. CS 475, Spring 2018 Concurrent & Distributed Systems

HY 345 Operating Systems

CS Lecture 3! Threads! George Mason University! Spring 2010!

Transcription:

Processes Prof. James L. Frankel Harvard University Version of 6:16 PM 10-Feb-2017 Copyright 2017, 2015 James L. Frankel. All rights reserved.

Process Model Each process consists of a sequential program Each process has its own: PC Registers Address Space Program Variables In essence, Virtual CPU Multiprogramming is running multiple processes in virtual parallel That is, quickly switching among processes to give the illusion that they are running simultaneously

Why Do We Want Processes? Allows processing to take place while waiting for other events When is this helpful? Some interactive users are idle while others are active (think nice timesharing) Some programs are waiting for I/O operations to complete Those programs may be blocked from execution waiting for an event to occur Enables fair sharing of a limited number of processors/cores Allows background processes to run (scavenging a disk, checking for new e- mail or text messages, UI remains responsive while tasks are in progress, etc.)

Processes The Process Model Multiprogramming of four programs Conceptual model of 4 independent, sequential processes Only one program active at any instant

Process Creation Occurs when: A computer is initialized (i.e., booted ) A process creation system call is invoked A user requests a new process for example, through a shell command This eventually invokes a process creation system call A batch job is initiated

Unix Process Creation Fork System Call fork(2) Same memory image Same environment settings Same open files Return value 0 to child PID (Process ID) of child to parent -1 on failure w/errno set appropriately After fork, the two processes have separate address spaces

Process Termination Occurs upon: Normal exit voluntary Error exit voluntary Fatal error involuntary Killed by another process involuntary

Unix Process Hierarchy In Unix, a process & all of its descendants form a process group In Windows, there is no process hierarchy

Process State Three states Running Actually utilizing the CPU currently Ready Could be running, but is not currently running because another process is utilizing the CPU Blocked Not able to run currently because it is waiting for some external event All possible state transitions are shown in the following diagram

Process State Transitions Process blocks waiting for event Running Unscheduled Scheduled Blocked Ready Blocking event occurs

Process Quantum Quantum is the length of time each process is allowed to run A process may yield its quantum prematurely The quantum is determined so that It is not too long so as to make processes unresponsive It is not too short so as to decrease the percentage of useful work accomplished by the processor There is fixed overhead to switch from one process to another

Process State Data is associated with each process Such data is usually stored in a PCB (Process Control Block) or in the Process Table Included in that data is Process Management Data Memory Management Data File/Device Management Data

Process Management Data Saved Registers PC PSW SP Process State Priority Scheduling Parameters PID Parent Process Process Group Signals Time When Started CPU Time Used Children s CPU Time Used Time of Next Alarm

Memory Management Data Pointer to text segment Pointer to bss segment Pointer to data segment Data structure for heap management Pointer to stack segment

File/Device Management Data Root directory Current working directory (CWD) Open file descriptors User ID Group ID

Interrupts Events that can interrupt the normal sequence of instruction execution Such events include: A timer has expired Timers may be one-shot or continuous Input operation ready Examples A character has been typed and is ready to be read A disk block has been read Output operation complete or output device ready for next output operation Examples A serial device is ready for the next character to be sent A serial device has completed sending its last buffered character Writing a disk block has completed A disk controller is ready for another block to be written A network controller is ready for another packet to be sent

Maskable vs. Non-Maskable Interrupts Most interrupts may be enabled or disabled as a group by a privileged program These are called Maskable Interrupts Usually there are instructions to accomplish this di disable interrupts ei enable interrupts Additionally, each interrupt usually needs to be separately enabled Associated with each interrupt is an interrupt priority Some high-priority interrupts cannot be disabled and a referred to as Non- Maskable Interrupts Non-recoverable Includes power failure, memory error, system restart, illegal instruction

Interrupt Vector Contains an entry for each class of interrupt that can occur Each entry is a pointer to code to handle that interrupt, a so-called interrupt handler or interrupt service routine May or may not include entries for non-maskable interrupts

Interrupt Behavior Hardware pushed PC & PSW Hardware loads new PC from appropriate interrupt vector table entry Software saves registers (often written in assembly language) Software (or hardware) may switch to a different stack Interrupt service routine (ISR) runs (often written in C) Handles the interrupt such as reading input and saving the read data into a buffer in RAM The interrupt may have been caused by a timer at quantum expiration Either ISR returns to point of interrupt or the scheduler decides which process to run next Assembly language code restores state of process to run

Threads Multiple threads of control (like processes), but with the same address space Some data is shared Still separate state, stacks, registers, PC, PSW No protection between threads of the same process

Thread Tradeoffs (1 of 2) Advantages Better concept for cooperating parallel processes Faster to start and to end Allow overlap of I/O & CPU work (for processes, too) Allow use of multiple CPUs (for processes, too) Sharing Shared global variables Separate stacks, but no memory protection between Same open files, child processes, alarms, signals, signal handlers, accounting information Separate thread state, registers, PC, PSW

Thread Tradeoffs (2 of 2) Why don t we always use threads instead of processes? No memory protection between threads in the same process Malicious thread could steal information or cause incorrect behavior Thread with an error could crash other threads in the same process May not want to share open files, child processes, alarms, signals, signal handlers, accounting information

The Thread Model Each thread has its own stack

Thread Usage (1) Word Processor A word processor with three threads

Thread Usage (2) Web Server A multithreaded Web server

Thread Usage Dispatcher and Workers Could be used for the web server in previous slide Thread roles: (a) One Dispatcher thread (b) Many Worker threads

POSIX Threads (pthread) pthread_create pthread_exit pthread_join pthread_yield pthread_attr_init pthread_attr_destroy

User Space vs. Kernel Space Threads User space No OS support required System traps are not required Scheduling algorithm can be per process Problems Blocking system calls (can create non-blocking wrappers) Page faults cause blocking How to preempt (timer may be used, has overhead, may not allow a sufficiently small interval) Blocking may be precisely why threads are desirable Kernel space Blocking is not a factor More overhead Need to determine which thread gets a signal Hybrid threads may be an answer

Implementing Threads in User Space A user-level threads package

Implementing Threads in the Kernel A threads package managed by the kernel

Hybrid Implementations Multiplexing user-level threads onto kernel- level threads

The errno Issue errno is a global variable in which an error number is returned by most Unix system calls This mechanism would cause problems for a thread environment Therefore, errno must be local to each thread within a process It is often desirable to allow some shared and some independent static data among threads

Making Single-Threaded Code Multithreaded Conflicts between threads over the use of a global variable

Thread Safety In addition to errno, there are other thread safety issues Reentrant library procedures malloc may not be arbitrarily interruptable Alternatively, wrappers may enforce single-threaded access to these routines, but eliminate parallel execution Reentrant vs. serially-reusable code Signals Stack expansion

Pop-Up Threads Creation of a new thread when message arrives (a) before message arrives (b) after message arrives

Interprocess Communication Race conditions Result depends on who runs precisely when Critical regions/sections Those portions of code which cannot be executed by more than thread/process in order to enforce correct behavior by avoiding race conditions There may be multiple classes of critical regions Think of critical regions as being named Only one process at a time can be in any one named critical region

Example of a Race Condition Bank Transactions Assume initial balance is 20 Process 1 is making a deposit balance += 50; /* Process 1 */ Process 2 is making a withdrawal balance -= 10; /* Process 2 */

Example of a Race Condition Low-level Instructions Process 1 is making a deposit r1 <- balance; /* Process 1 */ r1 <- r1 + 50; /* Process 1 */ balance <- r1; /* Process 1 */ Process 2 is making a withdrawal r1 <- balance; /* Process 2 */ r1 <- r1-10; /* Process 2 */ balance <- r1; /* Process 2 */

Example of a Race Condition Interleaving #1 Order #1 of execution of instruction balance <- 20; r1 <- balance; /* Process 1 */ r1 <- r1 + 50; /* Process 1 */ r1 <- balance; /* Process 2 */ r1 <- r1-10; /* Process 2 */ balance <- r1; /* Process 1 */ balance <- r1; /* Process 2 */ Final balance is 10 Deposit is lost

Example of a Race Condition Interleaving #2 Order #2 of execution of instruction balance <- 20; r1 <- balance; /* Process 2 */ r1 <- r1-10; /* Process 2 */ r1 <- balance; /* Process 1 */ r1 <- r1 + 50; /* Process 1 */ balance <- r1; /* Process 2 */ balance <- r1; /* Process 1 */ Final balance is 70 Withdrawal is lost

Example of a Race Condition Interleaving #3 Order #3 of execution of instruction balance <- 20; r1 <- balance; /* Process 1 */ r1 <- r1 + 50; /* Process 1 */ balance <- r1; /* Process 1 */ r1 <- balance; /* Process 2 */ r1 <- r1-10; /* Process 2 */ balance <- r1; /* Process 2 */ Final balance is 60 Nothing is lost

Critical Regions Mutual exclusion using critical regions

Effective Cooperating Parallel Processes 1. No two processes may be simultaneously inside their critical sections 2. No assumptions may be made about speeds or number of CPUs 3. No process running outside its critical section may block any process 4. No process should have to wait forever to enter its critical section

Mutual Exclusion (1 of 3) Disable interrupts Used by kernel, but dangerous for users Affects only one CPU/core Lock variable Doesn t work because access to the lock variable is not protected Strict alternation Requires equal work by both processes and alternation Requires busy waiting (wastes CPU time)

Mutual Exclusion through Strict Alternation (a) Process 0. (b) Process 1.

Mutual Exclusion (2 of 3) (Dekker s &) Peterson s solutions Requires busy waiting (wastes CPU time) In the following code, global variables are shared across processes and local variables are not shared This is crucial to understand how the following code works

Mutual Exclusion through Peterson s Solution

Mutual Exclusion (3 of 3) TSL Test and Set Lock Instruction Works across CPUs in a multiprocessor/multicore architecture Requires busy waiting (wastes CPU time)

Mutual Exclusion through TSL Instruction

Mutual Exclusion Without Busy Waiting Let s try blocking rather than busy waiting Remember, a process that is blocked does not use any CPU time Our algorithm will be a Producer-Consumer Problem Also known as the Bounded-Buffer Problem Possible solutions

Sleep and Wakeup Producer-consumer example with fatal race condition

Mutual Exclusion Implementing a producer and a consumer using sleep and wakeup Does *not* provide a race-free solution! wakeup s will be lost if the consumer is not already sleep ing Any wakeup s that may have occurred before sleep ing are not remembered

Semaphore Introduction Down (similar to sleep, but counted) Dijkstra named this P (for Proberen in Dutch, meaning try) Up (similar to wakeup, but counted) Dijkstra named this V (for Verhogen in Dutch, meaning raise) The value of a semaphore is the number of pending wake-ups The value is always non-negative

Semaphore Implementation down(*semaphore) /* similar to sleep, but counted */ down is implemented as an atomic action Checks to see if the semaphore is greater than 0 If so, the semaphore is decremented and down returns If not, put the process to sleep (i.e., blocks) and, when awakened, down repeats up(*semaphore) /* similar to wakeup, but counted */ up is implemented as an atomic action The semaphore is incremented If any process is sleeping waiting on this semaphore, one is awakened

Semaphores A correct producer-consumer example using semaphores

Implementation of Mutexes Using TSL Implementation of mutex_lock and mutex_unlock

Mutexes in Pthreads pthread_mutex_init pthread_mutex_destroy pthread_mutex_lock Acquire or block pthread_mutex_trylock Acquire or fail pthread_mutex_unlock Release

Monitor Example

Producer-Consumer Example Using Monitors Only one monitor procedure active at one time Condition variables: not counting, no accumulation, wait must precede signal Wait breaks out of the monitor until signaled

Message Passing The producer-consumer problem with N messages

Barriers Use of a barrier (a) processes approaching a barrier (b) all processes but one blocked at barrier (c) last process arrives, all are let through

CPU and I/O Usage by Processes CPU usage alternates with periods of waiting for I/O operations (a) a CPU-bound process (b) an I/O-bound process

Scheduling Goals

Scheduling Batch First-come First-served (FCFS) Shortest Job First (SJF) Better turnaround time Shortest Remaining Time Next (SRTN) Preemptive version of SJF Interactive Round Robin (RR) Quantum Priority RR within each priority class; Priority may decrease over time Multiple Queues May have different quantum size in each priority queue Shortest Process Next (SPN) Give more CPU time to newer processes Guaranteed Scheduling For real-time processes Lottery Scheduling Tickets distributed according to need; Choose at random Fair-Share Scheduling

Shortest Job First Scheduling for Batch Systems

Round-Robin Scheduling Round Robin Scheduling list of runnable processes list of runnable processes after B uses up its quantum

Priority Scheduling A scheduling algorithm with four priority classes

Real-Time System Scheduling Given m periodic events event i occurs within period P i and requires C i seconds Then the load can only be handled if m C i 1 i 1 P i