Docsity

Control Flow: Continuations, Exceptions, and Coroutines in CS421 Lecture 20 by Mark Hills , Study notes of Computer Science

Toggle sidebar
bg1
Outline
Overview
Continuations
Exceptions
Coroutines
CS421 Lecture 20: Control Flow1
Mark Hills
University of Illinois at Urbana-Champaign
July 25, 2006
1Based on slides by Mattox Beckman, as updated by Vikram Adve, Gul
Agha, and Elsa Gunter
Mark Hills CS421 Lecture 20: Control Flow
Outline
Overview
Continuations
Exceptions
Coroutines
Overview
Continuations
Exceptions
Coroutines
Mark Hills CS421 Lecture 20: Control Flow
Outline
Overview
Continuations
Exceptions
Coroutines
Objectives
By the end of this lecture, you should
◮be familiar with different kinds of control flow constructs
◮understand the basics of continuations and the Scheme
call/cc construct
◮understand exceptions, especially the approach taken by
modern OO languages like Java
◮know about coroutines at a high-level, including how they
work and what they can accomplish
Mark Hills CS421 Lecture 20: Control Flow
Outline
Overview
Continuations
Exceptions
Coroutines
Classes of Control Flow
We can break control flow up into a number of categories, based
on the purpose of the constructs.
◮Invocation
◮Direct calls: functions, subroutines
◮Indirect calls: function pointers, class metho ds, closures
◮Termination of Scope
◮Structured: break, break to a label, exceptions, CPS
◮Unstructured: goto, setjmp/longjmp, exit
◮Selection
◮Structured: if/then/else, continue, switch, case
◮Unstructured: goto, computed goto, labeled entries
Mark Hills CS421 Lecture 20: Control Flow
Outline
Overview
Continuations
Exceptions
Coroutines
Classes of Control Flow, cont.
◮Iteration
◮Precomputed iteration space: do, foreach
◮Dynamic iteration space: for, while, recursion
◮Concurrency
◮Manual: processes, threads, futures, coroutines
◮Automatic: constructs in concurrent/parallel frameworks for
reductions
◮Communication and synchronization techniques are critical
◮You should have come across many of these already:
if/then/else, switch/case, do, for, while, break, continue,
probably foreach, goto, exit
Mark Hills CS421 Lecture 20: Control Flow
Outline
Overview
Continuations
Exceptions
Coroutines
Continuations
Scheme and Call/CC
Examples
Summary
Continuations
At its core, the continuation is just “the rest of the computation”
– it tells us what we have left to do.
◮Continuations can be used to model many control flow
constructs
◮Continuation manipulation is a fundamental feature of Scheme
◮Also, very important to denotational semantics; continuations
allow modelling of complex control flow
Mark Hills CS421 Lecture 20: Control Flow
pf3
pf4
pf5

Partial preview of the text

Download Control Flow: Continuations, Exceptions, and Coroutines in CS421 Lecture 20 by Mark Hills and more Study notes Computer Science in PDF only on Docsity!

Overview Continuations Exceptions Coroutines

CS421 Lecture 20: Control Flow

Mark Hills

[email protected]

University of Illinois at Urbana-Champaign

July 25, 2006

Based on slides by Mattox Beckman, as updated by Vikram Adve, Gul

Agha, and Elsa Gunter

Mark Hills CS421 Lecture 20: Control Flow

Overview Continuations Exceptions Coroutines

Overview

Continuations

Exceptions

Coroutines

Mark Hills CS421 Lecture 20: Control Flow

Outline Overview Continuations Exceptions Coroutines

Objectives

By the end of this lecture, you should

◮ be familiar with different kinds of control flow constructs

◮ understand the basics of continuations and the Scheme

call/cc construct

◮ understand exceptions, especially the approach taken by

modern OO languages like Java

◮ know about coroutines at a high-level, including how they

work and what they can accomplish

Mark Hills CS421 Lecture 20: Control Flow

Outline Overview Continuations Exceptions Coroutines

Classes of Control Flow

We can break control flow up into a number of categories, based

on the purpose of the constructs.

◮ Invocation

◮ Direct calls: functions, subroutines

◮ Indirect calls: function pointers, class methods, closures

◮ Termination of Scope

◮ Structured: break, break to a label, exceptions, CPS

◮ Unstructured: goto, setjmp/longjmp, exit

◮ Selection

◮ Structured: if/then/else, continue, switch, case

◮ Unstructured: goto, computed goto, labeled entries

Mark Hills CS421 Lecture 20: Control Flow

Outline Overview Continuations Exceptions Coroutines

Classes of Control Flow, cont.

◮ Iteration

◮ Precomputed iteration space: do, foreach

◮ Dynamic iteration space: for, while, recursion

◮ Concurrency

◮ Manual: processes, threads, futures, coroutines

◮ Automatic: constructs in concurrent/parallel frameworks for

reductions

◮ Communication and synchronization techniques are critical

◮ You should have come across many of these already:

if/then/else, switch/case, do, for, while, break, continue,

probably foreach, goto, exit

Outline Overview Continuations Exceptions Coroutines

Continuations Scheme and Call/CC Examples Summary

Continuations

At its core, the continuation is just “the rest of the computation”

– it tells us what we have left to do.

◮ Continuations can be used to model many control flow

constructs

◮ Continuation manipulation is a fundamental feature of Scheme

◮ Also, very important to denotational semantics; continuations

allow modelling of complex control flow

Overview Continuations Exceptions Coroutines

Continuations Scheme and Call/CC Examples Summary

Call/CC

To do something interesting with a continuation, we first need to

get ahold of one. In Scheme, this is done using the call/cc

function.

◮ The continuation is represented as a function expecting one

argument

◮ The call/cc call also expects a function that takes one

argument as its argument

◮ When call/cc is called, the current control context is saved

and passed to the function argument of call/cc

◮ Invoking this argument then returns control to where we were

when we invoked call/cc

Mark Hills CS421 Lecture 20: Control Flow

Overview Continuations Exceptions Coroutines

Continuations Scheme and Call/CC Examples Summary

Call/CC Example 1

1 (define call/cc call-with-current-continuation)

The full name is a bit cumbersome, but some Schemes don’t define the

abbreviation...

1 (+ 1 (call/cc

2 (lambda (k)

3 (+ 2 (k 3)))))

◮ The continuation is (+ 1 []), where [] represents the

“hole” where the continuation result will be placed

◮ The final result is just 4 (1 + 3), since we never add 2 to the

result.

Mark Hills CS421 Lecture 20: Control Flow

Outline Overview Continuations Exceptions Coroutines

Continuations Scheme and Call/CC Examples Summary

Call/CC Example 2

1 (define list-product

2 (lambda (s)

3 (call/cc

4 (lambda (exit)

5 (let recur ((s s))

6 (if (null? s) 1

7 (if (= (car s) 0) (exit 0)

8 (* (car s) (recur (cdr s))))))))))

9 > (list-product ’(1 2 3 4 5))

11 > (list-product ’(1 2 0 3 4 5))

This allows us to “jump out” when we find a 0, meaning that the

product of the entire list is 0

Mark Hills CS421 Lecture 20: Control Flow

Outline Overview Continuations Exceptions Coroutines

Continuations Scheme and Call/CC Examples Summary

Continuations, Overall

◮ The good: Using continuations with call/cc gives us a

flexible way to encode jumps, meaning we could build up

features like exceptions.

◮ The bad: This could get cumbersome, though – if we have a

dedicated exception mechanism, even just syntactic sugar, it

would make programs clearer.

Mark Hills CS421 Lecture 20: Control Flow

Outline Overview Continuations Exceptions Coroutines

Error Handling Techniques Exceptions Exceptions in Java Evaluation

Error Handling

Historically, languages and language APIs have handled errors in

several different ways:

◮ Have functions return values, outside of the normal range of

return values, that represent errors;

◮ Return a success or error code from the function, requiring

actual return values to be in pointers or reference parameters;

◮ Pass an error handling routine (like a continuation) that the

normal routine can invoke when errors occur.

Outline Overview Continuations Exceptions Coroutines

Error Handling Techniques Exceptions Exceptions in Java Evaluation

Special Return Values

1 if ((he=gethostbyname(hostname)) == NULL) {

2 perror("clientConnect: failed to resolve ip address");

3 return HOSTNOTFOUND;

6 if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {

7 perror("clientConnect: failed to create socked");

8 return OTHERERROR;

Overview Continuations Exceptions Coroutines

Error Handling Techniques Exceptions Exceptions in Java Evaluation

Exceptions in Java

In Java, exceptions are objects like other objects in the system, and

are joined into the same inheritance hierarchy.

◮ Exceptions all extend class Throwable

◮ Most exceptions extend Exception, which is for checked

exceptions

◮ System exceptions extend RuntimeException or Error,

which are unchecked (do not need to be caught)

◮ Exceptions can be manually thrown with the throw statement

Mark Hills CS421 Lecture 20: Control Flow

Overview Continuations Exceptions Coroutines

Error Handling Techniques Exceptions Exceptions in Java Evaluation

Example: Java Exception Handler

1 ParallelTerm currentTerm = null;

2 try {

3 currentTerm = (ParallelTerm)definition.clone();

4 } catch (Exception e) {

5 System.err.println("Clone exception caught!");

6 e.printStackTrace();

7 System.exit(-1);

Mark Hills CS421 Lecture 20: Control Flow

Outline Overview Continuations Exceptions Coroutines

Error Handling Techniques Exceptions Exceptions in Java Evaluation

Multiple Exception Handlers

Exceptions in Java can have multiple exception handlers.

◮ Handlers are tried in order, with the first handler defined for

the runtime class of the exception or a parent of this class

being used

◮ Handlers for class Exception act as “else” cases, catching

any checked exception (and thus should come last in the list!)

◮ Uncaught exceptions must be listed in a throws clause of the

method

Mark Hills CS421 Lecture 20: Control Flow

Outline Overview Continuations Exceptions Coroutines

Error Handling Techniques Exceptions Exceptions in Java Evaluation

Example: Multiple Handlers and throw

1 try {

3 } catch (IOException e) {

5 throw new MigrateActorException(e.getMessage());

6 } catch (ClassNotFoundException e) {

8 throw new MigrateActorException(e.getMessage());

Mark Hills CS421 Lecture 20: Control Flow

Outline Overview Continuations Exceptions Coroutines

Error Handling Techniques Exceptions Exceptions in Java Evaluation

Exception Propagation

Exceptions work by “unwinding” the call stack until a proper

handler is found.

◮ In languages like C++, destructors for local objects must be

called

◮ Work typically done on function returns must be performed

(saved registers are set back to the proper values, stack space

is deallocated, etc)

◮ This unwinding may unwind all the way back to the start of

the program – this generally causes a default exception

handler surrounding the start of the program to be invoked

Outline Overview Continuations Exceptions Coroutines

Error Handling Techniques Exceptions Exceptions in Java Evaluation

Forcing Cleanup

Some languages include a finally block as part of exceptions:

◮ Used to indicate cleanup code that should always run at the

end of the exception handler block;

◮ called either when exception handler ends or before the

exception propagates up the stack;

◮ very complex semantics, since exceptions and finally blocks

can also throw exceptions.

Overview Continuations Exceptions Coroutines

Error Handling Techniques Exceptions Exceptions in Java Evaluation

Finally Example

This example is from p.448 of Scott’s Programming Language

Pragmatics:

1 FileReader myStream = null;

2 try {

3 myStream = new FileReader(new File("foo"));

4 parse(myStream);

5 } catch (EOFException e) {

6 System.out.println("Oops; input file too short.");

7 } finally {

8 myStream.close();

Mark Hills CS421 Lecture 20: Control Flow

Overview Continuations Exceptions Coroutines

Error Handling Techniques Exceptions Exceptions in Java Evaluation

Question: Are Checked Exceptions a Good Idea?

One debate over exceptions is whether having checked exceptions

is a good idea.

◮ Java says yes – checked exceptions are valuable, since a

programmer has to deal with any possible exceptions

◮ C++ and C# say no – checked exceptions lead to worthless

exception handlers that obfuscate the real source of

exceptions, since people just put in wrappers that “eat” the

exception to make the language happy

Mark Hills CS421 Lecture 20: Control Flow

Outline Overview Continuations Exceptions Coroutines

Coroutines Examples Internals

Coroutines

◮ Similar to continuation – represented as a closure with a code

location and referencing environment

◮ Call of coroutine is a non-local transfer of control (similar to a

goto, but more structured); referred to as transfer

◮ Difference with continuation – code location can change with

each call, so when we transfer we keep track of where we were

last

Mark Hills CS421 Lecture 20: Control Flow

Outline Overview Continuations Exceptions Coroutines

Coroutines Examples Internals

Coroutines

Coroutines basically give us multiple execution contexts existing

concurrently but only running one at a time.

◮ Can be used to model other control abstractions (iterators,

threads)

◮ Can be used for situations where we want to maintain

program state between calls to the coroutine

◮ Well suited to discrete event simulation

Mark Hills CS421 Lecture 20: Control Flow

Outline Overview Continuations Exceptions Coroutines

Coroutines Examples Internals

Coroutine Example: Beta

1 (# i: @Integer;

2 b: @| (# do (L: i+5->i; suspend;

3 restart L

4 :L)

5 exit i

7 do 10->i; b->i; i->putint;

8 b->i; i->putint

Here, we can call b as an incrementer, which will add 5 to i each

time it is called, and will remember where it left off in the code

(hence the need to restart).

Outline Overview Continuations Exceptions Coroutines

Coroutines Examples Internals

Couroutine Example 2: Beta

1 (# Factorial: @|

2 (# T: [100] @ Integer; N,Top: @Integer;

3 enter N

4 do 1->Top->T[1];

5 Cycle(#

6 do (if (Top<N) // True then

7 (Top+1,N)->ForTo

8 (#do T[inx-1]*i->T[inx]#);

9 N->Top

10 if);

11 N+1->N; SUSPEND;

13 exit T[N-1]

15 F: @Integer

16 do 4->Factorial->F; Factorial->F; 3->Factorial->F;