Exception handling. Exceptions can be created by the hardware or by software: Examples. Printer out of paper End of page Divide by 0

Similar documents
Concurrency. Lecture 14: Concurrency & exceptions. Why concurrent subprograms? Processes and threads. Design Issues for Concurrency.

Exception Handling: Control. Exception handling is the control of error conditions or other unusual events during the execution of a program.

Performance Throughput Utilization of system resources

Deadlock. Concurrency: Deadlock and Starvation. Reusable Resources

Concurrency: Deadlock and Starvation. Chapter 6

14. Exception Handling

Operating Systems: William Stallings. Starvation. Patricia Roy Manatee Community College, Venice, FL 2008, Prentice Hall

Chapter Machine instruction level 2. High-level language statement level 3. Unit level 4. Program level

UNIT 3

Ch 9: Control flow. Sequencers. Jumps. Jumps

Multitasking / Multithreading system Supports multiple tasks

IT 540 Operating Systems ECE519 Advanced Operating Systems

Chapter 14. Exception Handling and Event Handling 异常处理和事件处理. 孟小亮 Xiaoliang MENG, 答疑 ISBN

Chapter 5 Concurrency: Mutual Exclusion and Synchronization

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Chapter 7 Control I Expressions and Statements

Resource management. Real-Time Systems. Resource management. Resource management

Unix System Programming - Chapter 8

Chapter 14. Exception Handling and Event Handling ISBN

Chapter 5 Concurrency: Mutual Exclusion. and. Synchronization. Operating Systems: Internals. and. Design Principles

Chapter 14. Exception Handling and Event Handling

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

Exceptions Programming 1 C# Programming. Rob Miles

Exceptions. Exceptions. Exceptional Circumstances 11/25/2013

Concurrent Programming

Chapter 13 Topics. Introduction. Introduction

Summary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data

Process Management And Synchronization

Dealing with Issues for Interprocess Communication

Last Class: Synchronization. Review. Semaphores. Today: Semaphores. MLFQ CPU scheduler. What is test & set?

CS Operating Systems

CS Operating Systems

Lecture 9: Control Flow

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Real-Time Systems. Lecture #4. Professor Jan Jonsson. Department of Computer Science and Engineering Chalmers University of Technology

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Last Class: Deadlocks. Today

Concurrent Programming. CS105 Programming Languages Supplement

College of Computer & Information Science Spring 2010 Northeastern University 26 January 2010

CPS 506 Comparative Programming Languages. Programming Language Paradigms

Global shared variables. Message passing paradigm. Communication Ports. Port characteristics. Sending a message 07/11/2018

Lecture 8: September 30

Java Threads and intrinsic locks

What's wrong with Semaphores?

CMSC 433 Programming Language Technologies and Paradigms. Composing Objects

Deviations are things that modify a thread s normal flow of control. Unix has long had signals, and these must be dealt with in multithreaded

Lecture 6 (cont.): Semaphores and Monitors

National University. Faculty of Computer Since and Technology Object Oriented Programming

Signals are a kernel-supported mechanism for reporting events to user code and forcing a response to them. There are actually two sorts of such

Structuring the Computation. Structuring the Computation

(In columns, of course.)

Synchronization for Concurrent Tasks

Chapter 13. Concurrency ISBN

St. MARTIN S ENGINEERING COLLEGE Dhulapally, Secunderabad

A read or write being atomic means that its effect is as if it happens instantaneously.

Resource Sharing & Management

1 Process Coordination

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Chapter 5 Asynchronous Concurrent Execution

Dr. Rafiq Zakaria Campus. Maulana Azad College of Arts, Science & Commerce, Aurangabad. Department of Computer Science. Academic Year

EE458 - Embedded Systems Lecture 8 Semaphores

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

Iterators. Lecture 24: Iterators & Exceptions. Implementing Iterators. When Good Programs Go Bad! - where! Abstract over control structures (in Clu)!

R13 SET Discuss how producer-consumer problem and Dining philosopher s problem are solved using concurrency in ADA.

INSTITUTE OF AERONAUTICAL ENGINEERING

CS 31: Introduction to Computer Systems : Threads & Synchronization April 16-18, 2019

Concurrency - Topics. Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads

Operating Systems ECE344

HY345 - Operating Systems

Chapter 6 Concurrency: Deadlock and Starvation

Opera&ng Systems ECE344

Deadlock and Starvation

CONCURRENT/DISTRIBUTED PROGRAMMING ILLUSTRATED USING THE DINING PHILOSOPHERS PROBLEM *

The SPIN Model Checker

Sequencers. Markus Roggenbach. 18. März 2004

Control Abstraction. Hwansoo Han

Concurrency Problems Signals & Synchronization Semaphore Mutual Exclusion Critical Section Monitors

! The Process Control Block (PCB) " is included in the context,

Concurrent Processes Rab Nawaz Jadoon

Roadmap. Tevfik Ko!ar. CSC Operating Systems Fall Lecture - III Processes. Louisiana State University. Processes. September 1 st, 2009

Deadlock. Lecture 4: Synchronization & Communication - Part 2. Necessary conditions. Deadlock handling. Hierarchical resource allocation

CSE 153 Design of Operating Systems

Processes and More. CSCI 315 Operating Systems Design Department of Computer Science

PROCESS SYNCHRONIZATION

CS3502 OPERATING SYSTEMS

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

Unix System Programming - Chapter 2, part a

Concurrency Race Conditions and Deadlocks

Concurrency, Mutual Exclusion and Synchronization C H A P T E R 5

Operating Systems Overview. Chapter 2

Lecture 9: Parameter Passing, Generics and Polymorphism, Exceptions

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Concurrency: a crash course

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

CS-537: Midterm Exam (Spring 2001)

POSIX / System Programming

Lecture 2: Architectural Support for OSes

Last Class: Synchronization

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018

Transcription:

Exception handling Events in a program sometimes occur at unpredictable times, I.e., apparently randomly. That is, the occurrence is an exception to the normal sequencing of events. Such events are called exceptions, and programming language constructed designed to handle these are called exception handlers. Exceptions can be created by the hardware or by software: Examples Power failure Printer out of paper End of page Divide by 0 End of array reached Hardware generated Software generated 1

Testing for exceptions Although software exceptions can be tested in the code, the existence of an exception handling mechanism relieves the programmer the burden of constantly checking for this condition. Causing an exception: to raise an exception or throw an exception. Example: End-of-page Without exceptions, need to test at each print statement: print data; if end-of-page then call newpage(); With automatic exceptions, setup mechanism: [PL/I example:] On endpage begin put page; end; /* Resume execution */ can write output without checking end-page condition each time 2

Implementation of exceptions Exceptions come from two sources: conditions detected by the virtual machine, and conditions generated by the semantics of the programming language. In the former case, operating system exceptions may be raised directly by hardware interrupts or traps, such as arithmetic overflow, or they may be raised in support software, such as end-of-file condition. In C, the programmer has direct access to these signals processed by the operating system. The programmer may enable an interrupt (e.g., the sigaction function in Unix, which specifies a procedure that gets invoked when the given signal is raised). 3

Exceptions in ML One can throw an exception and a handler will catch the exception. (More limited than PL/I example. Need to explicitly raise an exception.): fun dodivide(a,b) = if b=0 then raise baddenominator else a/b; fun divide(a,b) = dodivide(a,b) handle baddenominator => (print Divide error ; 0.0); Note: dodivide is within dynamic scope of divide. Semantics if exception is raised: - If no handler, end function - Check dynamic scope of executing procedures to look for appropriate handler - If handler, execute handler, then return to exception point (e.g., print message and return 0.0 as default value in above example.) 4

Exceptions in C++ try clause implements exceptions. Similar to ML: try { statements... If b=0 throw baddenominator; } catch baddenominator {Do something;}; Propagating exceptions: If no local exception handler, who catches exception? Usually dynamic links checked for handler try statement terminates after handling exception. 5

Exceptions in Ada procedure Sub is Bad_Data_Value: exception; -other declarations for Sub begin -statements for normal processing in Sub raise Bad_Data_Value -- to raise this exception exception when Bad_Data_Value => -handler for bad data values when Constraint_Error => -handler for predefined exception Constraint_Error when others => -handler for all other exceptions end; [Constraint_Error (e.g., number too large) is a built-in exception in Ada.] 6

Propagating exceptions the place at which an exception occurs is not the best place to handle it a particular exception is usually defined in terms of the dynamic chain of subprogram activations each activation record needs to record those active exceptions being passed from calling procedure propagating exceptions allows a subprogram to remain as a programmer-defined abstract operation even in processing exceptions: a subprogram may interrupt its normal processing and raise an exception. to the caller, the effect of a subprogram's raising an exception is the same as a primitive operation's raising an exception if the subprogram does not handle the exception. if the exception is handled within the subprogram, then the subprogram returns in the normal way, and the caller is never aware that an exception has been raised. 7

More on implementation of exceptions the language translator may insert additional instructions. For example, to detect Index_Check caused by an invalid array subscript, the translator inserts instructions at each reference to an array, such as A[I,J], to determine whether the values of I and J are within the declared bounds. Unless the hardware or operating system provides the exception checking, checking for an exception requires software simulation. Often this cost is large. For example, it may take longer to perform the subscript bounds check on A[I,J] than it does to access the element of the array. Because of this extra cost, most languages provide a means to turn off checking for exceptions in parts of the program where the programmer determines it is safe to do so [e.g., pragma Supress(Index_Check) in Ada]. Note: programmers are notoriously bad in determining when it is safe to do so. 8

Assertions An assertion is a predicate that checks for an invalid value and then raises an exception: In C++: #include <assert.h>... assert(x,y); In C++ it is really a macro that generates: if (x>y) {/* Print error message */} (Compare assertions to pre- and postconditions of axiomatic verification in Section 4.2.4.) 9

Issues in synchronization Easy to do - Context switching (and statement, fork() function, task creation) Hardware virtual memory makes it easy for operating system to create independently executing tasks in their own address space Hard to do - Synchronization. How to pass information reliably among a set of independently executing parallel tasks. Consider and statement discussed previously: What is output that is printed? I = 1; I = I+1 and I = I-1 and write(i); write(i) Both first and second write can be 0, 1 or 2. Why? 10

Parallel soup (1) I = I+1 and (2) I = I-1 and (3) write(i); (4) write(i) If execution order is (1)(2)(3)(4), output is <1,1> If execution order is (1)(3)(2)(4), output is <2,1> If execution order is (2)(3)(1)(4), output is <0,1> How to get second write of 0: (1) I=I+1 is not a single operation. It is usually 3 instructions: Load from I, Add 1, store into I. What if context switch between instructions 1 and 2? (2) I=I-1 will set I to 0 then context switch back to (1) causes original value of I to be incremented to 2, which is printed as <2,2> If I=I-1 is executed first, we could get <0,0>, etc. 11

Critical regions A critical region is a sequence of program statements within a task where the task is operating on some data object shared with other tasks. Must use some mechanism to access this data: Semaphores Messages Monitors Rendezvous 12

Mutual exclusion 1. Mutual exclusion - Only one process can be executing a given section of code at one time. block(x) - block semaphore X. wakeup(x) - unblock semaphore X block(x) - if x is free, grab x, else wait until it is free wakeup(x) - free x and start any process waiting on x Example again: I = 1; block(a); I = I+1; wakeup(a) and block(a); I = I-1; wakeup(a) and block (A); write(i); wakeup(a) write(i) Output: Second write is always I=1, but first write can be 0, 1 or 2, depending upon which and statement executes first. 13

Semaphores 2. P-V semaphores (Dijkstra). P(X) { If X> 0 continue, else wait until X > 0. X = X-1 (in unit time)} V(X) { X = X+1 (in unit time)} P acts as a gate to limit access to tasks. In addition, you can use the semaphore as a counter to control how much access you need. Buffer manager: Initialization:{ counter = number of buffers available}; GetBuffer: { P(counter}, return buffer and process data}; FreeBuffer: { Put buffer on free list; V{counter}}; In GetBuffer, if no buffers are available, the program will wait until some other process issues a FreeBuffer to unfreeze the blocked process. 14

Multiple address spaces P-V assume all semaphores are addressable by all waiting tasks. When processes execute in different address spaces (e.g., on different machines), semaphores don't work. Messages can be used: send(a) - Send a message to pipe A. receive(a) - Receive a message on pipe A. If no pending message, wait until one shows up. Sample Input-Process-Output loop: P1: do loop P2: do loop P3: do loop Get data; Receive(P2, data) Receive(P3, data); Send(P2,data); Process data; Print data end Send(P3, data) end end Synchronization can be handled by sending messages in both directions: Pipe AB sends from A to B. Pipe BA sends from B to A. 15

Problem: Deadlock Process A: Block(X); Block(Y);... Do something Wakeup(X); Wakeup(Y); Process B: Block(Y); Block(X);... Do something Wakeup(X); Wakeup(Y) If process A does Block(X) at same time process B does Block(Y), then Both will succeed and then Both will wait for the other resource forever An unlikely occurrence, but it CAN happen. 16

Synchronization in Ada Rendezvous in Ada: Sender issues call DataReady Receiver issues accept DataReady. Either waits for other to reach this point. accept DataReady do -- Entry point for task for sender to do call DataReady -- process synchronization taask end; How to prevent receiver of task to be blocked- Use guarded if (select statement)... 17

Ada rendezvous select when Device1Status = ON => accept Ready1 do... end; or when Device2Status = ON => accept Ready2 do... end; or when Device3Status = connected => accept Ready3 do... end; else... -- No device is ready; do something end select; rendezvous - Task waits for either of Device 1, 2, or 3, and if none are ON, does something else 18

Monitors A monitor is a shared data object together with the set of operations that may manipulate it (i.e., an abstract data type) A task may manipulate the shared data object only by using the defined operations (i.e., data is encapsulated) To enforce mutual exclusion, require that at most one of the operations defined for the data object may be executing at any given time. We could implement monitors in Java or C++ as classes 19

Java threads Which synchronization mechanism does Java use? 20