Ch 9: Control flow Sequencers 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 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 20-11-2008 PAGE 0 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 1 Jumps 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 (E 1 ) C 1 else { C 2 goto X; C 3 ; while (E 2 ) { C 4 ; X: C 5 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 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 2 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 3
Jumps Escapes 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 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 20-11-2008 PAGE 4 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 5 Exceptions 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 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 of it C++ and Java, being object-oriented languages, treat exceptions as objects / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 6 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 7
Exceptions Exceptions Java has a built-in Exception class every exception is a subclass of Exception every exception represents a different abnormal situation try C 0 catch (T 1 I 1 ) C 1 catch (T n I n ) C n finally C f Able to catch any exception from class T 1 or ort n if C 0 throws an exception of type T i handler C i will be executed with identifier I i bound to that exception 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 20-11-2008 PAGE 8 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 9 Exceptions Exceptions Method annual rainfall data may catch the NumberFormatException static float[] readannual(bufferedreader input) throws IOException { try { float r = readfloat(input); catch (NumberFormatException e) { The main program calls readannual and deals with the IOException static void main() { float[] rainfall; try { rainfall = readannual(); catch (IOException e) { / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 10 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 11
Ch 10: Concurrency Programs and processes 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 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 20-11-2008 PAGE 12 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 13 Problems with concurrency 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 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 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 14 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 15
Problems with concurrency 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 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 20-11-2008 PAGE 16 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 17 Problems with concurrency Process interactions 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 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 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 18 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 19
Process interactions 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 Competing processes Commands B and C are competing if they need exclusive access to the same resource r Let B be the sequence B 1 ; B 2 ; B 3 Let C be the sequence C 1 ; C 2 ; C 3 B 1, C 1, B 3, C 3 are independent, none need r B 2 and C 2 both need r, so they cannot take place simultaneously, they are critical section wrtr B C may be executed as: ; B 2 ; ; C 2 ; ; C 2 ; ; B 2 ; but not as ; B 2 C 2 ; / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 20 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 21 Process interactions Concurrency primitives Communicating processes let B be the sequence B 1 ; B 2 ; B 3 let C be the sequence C 1 ; C 2 ; C 3 there is communication from B to C if B 2 produces data that C 2 consumes, so B 2 must end before C 2 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 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 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 22 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 23
Concurrency primitives 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 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 20-11-2008 PAGE 24 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 25 Concurrency primitives 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 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 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 26 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 27
Languages with concurrency primitives Object-oriented languages, e.g. Java with threads Specification languages mcrl2 CHI POOSL Scripting languages 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 / Faculteit Wiskunde en Informatica 20-11-2008 PAGE 28 Architectural Layers ToolBus Architecture Coordination Representation Representation Computation Computation Single Component Single Component Cooperating Components ToolBus Tools Coordination Representation ATerms Computation common data exchange format
ToolBus scripts: processes Send, receive message (handshaking) Send/receive notes (broadcasting) Subscription to notes Dynamic process creation Absolute/relative delay, timeout 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 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) 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
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 Composite process expressions One of the atomic processes mentioned above delta (deadlock), tau (silent step) P 1 + P 2 : choice (non-deterministic) P 1. P 2 : sequential composition P 1 P 2 : parallel composition P 1 * P 2 : repetition Composite process expressions P(T 1, T 2,...): a named process (with optional parameters) will be replaced by its definition create(p(t 1, T 2,...), Pid?): dynamic process creation V := Expr: evaluate Expr and assign result to V if Expr then P 1 else P 2 fi if Expr then P 1 fi = if Expr then P 1 else delta fi 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
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) 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 ) 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 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(pname 1,..., Pname n ) Each Pname is optionally followed by parameters