Ch 9: Control flow Sequencers We will study a number of - - PowerPoint PPT Presentation

ch 9 control flow sequencers
SMART_READER_LITE
LIVE PREVIEW

Ch 9: Control flow Sequencers We will study a number of - - PowerPoint PPT Presentation

Ch 9: Control flow Sequencers We will study a number of alternatives A sequencer is a language construct to transfer control to some other point in a program, destination traditional sequencers: A sequencer implements a flow of


slide-1
SLIDE 1

/ Faculteit Wiskunde en Informatica

PAGE 0 20-11-2008

Ch 9: Control flow

  • We will study a number of alternatives
  • traditional sequencers:

− sequential − conditional − iterative

  • jumps, low-level sequencers to transfer control
  • escapes, sequencers to transfer control out of

commands and procedures

  • exceptions, sequencers to signal abnormal situations

/ Faculteit Wiskunde en Informatica

PAGE 1 20-11-2008

Sequencers

  • A sequencer is a language construct to transfer

control to some other point in a program, destination

  • A sequencer implements a flow of control

/ Faculteit Wiskunde en Informatica

PAGE 2 20-11-2008

Jumps

  • A jump transfers control to a specified program point
  • A jump has typical the form goto L; and transfer the control to

program point L, which is a label if (E1) C1 else { C2 goto X; } C3; while (E2) { C4; X: C5 }

/ Faculteit Wiskunde en Informatica

PAGE 3 20-11-2008

Jumps

  • Unrestricted jumps lead to spaghetti code, thus hard to understand,

see http://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF

  • Most programming languages support gotos
  • Java refuses jumps, because it supports higher-level escapes and

exceptions

  • Some languages have restrictions:
  • the jump goto L; is legal only within the scope of L

− in C the scope of each label is the smallest enclosing block: − jumps within a block − jumps from a block to an enclosing one − jumps into a block from outside is not allowed

slide-2
SLIDE 2

/ Faculteit Wiskunde en Informatica

PAGE 4 20-11-2008

Jumps

  • C restricts jumps because a jump out of a block

must destroy the local variables

  • Jumps out of a procedure should lead to destroying

local variables and termination of procedure activation

  • Jumps out of a recursive procedure is even more

complicated

  • Jumps introduce unwanted complexity in the

semantics of high-level programming languages

/ Faculteit Wiskunde en Informatica

PAGE 5 20-11-2008

Escapes

  • An escape is a sequencer that terminates the execution of a

textually enclosing command or procedure

  • In C, C++, Java: break sequencer to break loops
  • In C, C++, Java: return sequencer to break loops and end

procedures

  • multiple return sequencers in a procedure is hard to

maintain

  • Escapes are restricted so that control cannot be transfer out of

procedures

  • A halt sequencer stops the entire program
  • exit() in C

/ Faculteit Wiskunde en Informatica

PAGE 6 20-11-2008

Exceptions

  • Exceptions are a mechanism to deal with abnormal

situations:

  • arithmetic operation overflows
  • uncompleted input/output operations
  • Exceptions take of two things:
  • error handling
  • Controlled termination of flow of control

/ Faculteit Wiskunde en Informatica

PAGE 7 20-11-2008

Exceptions

  • Code that detects an abnormal situation throws an

exception

  • the exception can be caught in another part of the

program

  • programmer have control over exceptions and handling
  • f it
  • C++ and Java, being object-oriented languages, treat

exceptions as objects

slide-3
SLIDE 3

/ Faculteit Wiskunde en Informatica

PAGE 8 20-11-2008

Exceptions

  • Java has a built-in Exception class
  • every exception is a subclass of Exception
  • every exception represents a different abnormal situation

try C0 catch (T1 I1) C1 … catch (Tn In) Cn finally Cf

  • Able to catch any exception from class T1 or … or Tn
  • if C0 throws an exception of type Ti handler Ci will be

executed with identifier Ii bound to that exception

/ Faculteit Wiskunde en Informatica

PAGE 9 20-11-2008

Exceptions

  • Exceptions can be caught at various levels:

static float readFloat(BufferedReader input) throws IOException, NumberFormatException { … if (…) throw new IOException(“end of input”); String literal = …; float f = Float.parseFloat(literal); return f; }

  • Float.parseFloat throws the NumberFormatException

/ Faculteit Wiskunde en Informatica

PAGE 10 20-11-2008

Exceptions

  • Method annual rainfall data may catch the NumberFormatException

static float[] readAnnual(BufferedReader input) throws IOException { … try { float r = readFloat(input); … } catch (NumberFormatException e) { … } … }

/ Faculteit Wiskunde en Informatica

PAGE 11 20-11-2008

Exceptions

  • The main program calls readAnnual and deals with the IOException

static void main() { float[] rainfall; … try { rainfall = readAnnual(); … } catch (IOException e) { … } … }

slide-4
SLIDE 4

/ Faculteit Wiskunde en Informatica

PAGE 12 20-11-2008

Ch 10: Concurrency

  • Why concurrency?
  • program design becomes more complex
  • testing becomes less effective
  • historically, improvement of efficiency via

− multiprogramming systems, usage of idle resources

  • currently, end of Moore’s law, efficiency gain via

− multi-core processors

/ Faculteit Wiskunde en Informatica

PAGE 13 20-11-2008

Programs and processes

  • A sequential process is a totally ordered set of steps
  • each step is a change of state
  • A sequential program specifies the state changes of

a sequential process

  • A concurrent program specifies the possible state

changes of 2 or more sequential processes

/ Faculteit Wiskunde en Informatica

PAGE 14 20-11-2008

Problems with concurrency

  • Nondeterminism:
  • sequential programs are deterministic
  • collateral and nondeterministic conditional commands

may introduce unpredictability in sequential programs − compiler is free to determine the order of execution − different compilers may lead to different behavior

  • A concurrent program is genuinely nondeterministic

even for a specific compiler − incorrect concurrent programs may behave correctly in general, but have sometimes unpredictable behavior

/ Faculteit Wiskunde en Informatica

PAGE 15 20-11-2008

Problems with concurrency

  • Speed dependence
  • sequential programs are speed-independent because

correctness does not depend on execution speed

  • concurrent programs are speed-dependent

− behavior depends on the relative speed at which its constituent sequential processes run − if absolute speeds are considered, outside world, we have real-time behavior − if the outcome is speed-dependent, there is a race condition

slide-5
SLIDE 5

/ Faculteit Wiskunde en Informatica

PAGE 16 20-11-2008

Problems with concurrency

  • Deadlock means that processes are unable to make progress

because of mutually incompatible demands for resources

  • mutual exclusion: a process may be given exclusive access

to resources

  • incremental acquisition: a process holds previously acquired

resource while waiting for new resources

  • no preemption: resources cannot be removed from a process

until it voluntarily releases them

  • circular waiting: a cycle of resources or processes in which

each process is waiting for resources that are held by the next process in the cycle

/ Faculteit Wiskunde en Informatica

PAGE 17 20-11-2008

Problems with concurrency

  • Solutions for deadlocks:
  • Ignore them and restart system if it occurs
  • Recovery by detecting and kill involved processes
  • Prevention by remove some of the preconditions
  • Avoid by scheduling of resources

/ Faculteit Wiskunde en Informatica

PAGE 18 20-11-2008

Problems with concurrency

  • Starvation
  • A concurrent program has the liveness property if it is

guaranteed that every process will make some progress over a sufficiently long period of time − Free of deadlock − Fair scheduling

  • Fair scheduling means that no process needing a

resource is indefinitely prevented from obtaining it

/ Faculteit Wiskunde en Informatica

PAGE 19 20-11-2008

Process interactions

  • Sequential and collateral commands do not allow

simultaneously execution of commands

  • The parallel command “B || C” indicates that B and

C may executed simultaneously or arbitrarily interleaved

slide-6
SLIDE 6

/ Faculteit Wiskunde en Informatica

PAGE 20 20-11-2008

Process interactions

  • Independent processes:
  • commands B and C are independent if the execution of

B has no effect on the execution of C, and vice versa

  • concurrent composition of independent processes is

deterministic

/ Faculteit Wiskunde en Informatica

PAGE 21 20-11-2008

Process interactions

  • Competing processes
  • Commands B and C are competing if they need exclusive

access to the same resource r − Let B be the sequence B1; B2; B3 − Let C be the sequence C1; C2; C3 − B1, C1, B3, C3 are independent, none need r − B2 and C2 both need r, so they cannot take place simultaneously, they are critical section wrt r − B || C may be executed as: − …; B2; … ; C2; … − …; C2; … ; B2; … − but not as …; B2||C2; …

/ Faculteit Wiskunde en Informatica

PAGE 22 20-11-2008

Process interactions

  • Communicating processes
  • let B be the sequence B1; B2; B3
  • let C be the sequence C1; C2; C3
  • there is communication from B to C if B2 produces data

that C2 consumes, so B2 must end before C2 starts

  • Thus B || C has the same behavior as B; C
  • Processes B and C intercommunicate if there is

communication in both directions: − B || C yields numerous outcomes

/ Faculteit Wiskunde en Informatica

PAGE 23 20-11-2008

Concurrency primitives

  • Process until now was a flow of control through a program
  • a conventional, heavyweight, process is a program, which involves:

− an address space − allocation of main storage, − share of CPU time − access to files, devices, etc. − context switching from one process to another involves a lot of time

  • a thread is a lightweight alternative

− flow of control through a program without computational resources − switching of threads involves swapping of content of working registers

slide-7
SLIDE 7

/ Faculteit Wiskunde en Informatica

PAGE 24 20-11-2008

Concurrency primitives

  • Process creation and control
  • create a new child process
  • load program code to be executed by a process
  • start execution of a process
  • suspend execution of a process
  • resume execution of a (suspended) process
  • let a process stop at the end of its execution
  • let the creator wait for the process to stop
  • destroy a stopped process, freeing resources
  • create, load, start are combined into fork
  • wait and destroy into join

/ Faculteit Wiskunde en Informatica

PAGE 25 20-11-2008

Concurrency primitives

  • Process creation and control
  • abstract operations for competition in order to make the

critical sections disjoint in time − acquire(r) to gain exclusive access to resource r − relinquish(r) to give up exclusive access − if resource r is already allocated, acquire(r) blocks the process it calls it − if resource r is freed, processes waiting for access are unblocked and rescheduled

  • abstract operations for (synchronous) communication

− transmit(m) called by a sender to send m − receive(m) called by a receiver to wait for m − asynchronous communication via broadcasting

/ Faculteit Wiskunde en Informatica

PAGE 26 20-11-2008

Concurrency primitives

  • Interrupts
  • ending a concurrent input/output operation is a

infrequent operation to which the CPU should respond quickly

  • ending input/output operations causes interrupts

/ Faculteit Wiskunde en Informatica

PAGE 27 20-11-2008

Concurrency primitives

  • Spin locks and wait-free algorithms
  • On a multiprocessor several processes may be executed

simultaneously

  • Most algorithms, Dekker’s algorithm (presented by Dijkstra),

Petterson’s algorithm, Simpson’s algorithm are complex and their behavior maybe corrupted by compiler optimizations

  • Primitives should be built into the language
  • events
  • semaphores
  • messages
  • remote procedure calls
slide-8
SLIDE 8

/ Faculteit Wiskunde en Informatica

PAGE 28 20-11-2008

Languages with concurrency primitives

  • Object-oriented languages, e.g. Java with threads
  • Specification languages
  • mCRL2
  • CHI
  • POOSL
  • Scripting languages
  • ToolBus

Intermezzo: ToolBus

  • Coordination: the way in which program and

system parts interact (procedure calls, RMI, ...)

  • Representation: language and machine neutral data

exchanged between components

  • Computation: program code that carries out a

specialized task

A rigorous separation of coordination from computation is the key to flexible and reusable systems

Cooperating Components

Intermezzo: ToolBus

  • Architectural Layers

Single Component Representation Computation Single Component Representation Computation Coordination

Intermezzo: ToolBus

  • ToolBus Architecture

ToolBus Coordination Representation Computation Tools ATerms common data exchange format

slide-9
SLIDE 9

Intermezzo: ToolBus

  • ToolBus scripts: processes
  • Send, receive message (handshaking)
  • Send/receive notes (broadcasting)
  • Subscription to notes
  • Dynamic process creation
  • Absolute/relative delay, timeout

Intermezzo: ToolBus

  • ToolBus scripts: tools
  • Execute/terminate tools
  • Connect/disconnect tools
  • Communication between process and tool is

synchronous

  • Process can send evaluation request to tool (which

returns a value later on)

  • Tool can generate events to be handled by the

ToolBus

Intermezzo: ToolBus

  • Process communication: messages
  • Messages used for synchronous, two-party

communication between processes

  • snd-msg and rec-msg synchronize sender/receiver
  • Communication is possible if the arguments match
  • There is two-way data transfer between sender and

receiver (using result variables)

Intermezzo: ToolBus

  • Process communication: notes
  • Notes used for asynchronous, broadcasting

communication between processes

  • Each process must subscribe to the notes it wants to

receive

  • Each process has a private note queue on which

snd-note, rec-note and no-note operate

slide-10
SLIDE 10

Intermezzo: ToolBus

  • Process communication
  • subscribe to notes of a given form

− subscribe(compute(<str>,<int>))

  • unsubscribe from certain notes
  • snd-note to all subscribers

− snd-note(compute(E,V))

  • rec-note: receive a note of a given form
  • no-note received of given form

Intermezzo: ToolBus

  • Composite process expressions
  • One of the atomic processes mentioned above
  • delta (deadlock), tau (silent step)
  • P1+ P2: choice (non-deterministic)
  • P1. P2: sequential composition
  • P1|| P2: parallel composition
  • P1* P2: repetition

Intermezzo: ToolBus

  • Composite process expressions
  • P(T1, T2, ...): a named process (with optional

parameters) will be replaced by its definition

  • create(P(T1, T2, ...), Pid?): dynamic process

creation

  • V := Expr: evaluate Expr and assign result to V
  • if Expr then P1 else P2 fi
  • if Expr then P1 fi =

if Expr then P1 else delta fi

Intermezzo: ToolBus

  • Process definitions
  • Process definition: process Pname Formals is P
  • Formals are optional and contain a list of formal

parameter names

− process MakeWave(N : int) is ...

  • All variables (including formals) must be declared

and have a type

  • let VarDecls in P endlet introduces variables:

− let E : str, V : int in ... endlet

slide-11
SLIDE 11

Intermezzo: ToolBus

  • Tools:
  • Tools have to be executed or connected before they

can be used

  • Requires a tool definition: tool ui is { ... }
  • Introduces a new type, e.g. ui
  • Execute a tool: execute(ui, Uid?)
  • Receive connection request:

rec-connect(ui, Uid?)

  • Tool identification is assigned to Uid (of type uid)

Intermezzo: ToolBus

  • Tools:
  • snd-terminate: terminate an executing tool

− snd-terminate(Tid)

  • rec-disconnect: receive disconnection request

from tool

− rec-disconnect(Uid)

  • shutdown: terminate the whole ToolBus

− shutdown(“Auction ends”)

Intermezzo: ToolBus

  • Tools
  • snd-eval, rec-value: request tool to evaluate a

term, and receive the resulting value from tool − initiative: ToolBus

  • snd-do: request tool to perform some action, there

is no reply − initiative: ToolBus

  • rec-event, snd-ack-event: receive event from tool,

acknowledge it after appropriate processing − initiative: tool

Intermezzo: ToolBus

  • Tscripts
  • a Tscripts consists of

− a list of process and tool definitions − a single ToolBus configuration

  • a ToolBus configuration describes the initial set of

active processes in the ToolBus:

− toolbus(Pname1, ..., Pnamen)

− Each Pname is optionally followed by parameters