Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication...

24
Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization

Transcript of Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication...

Page 1: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Program Control

Iteration and Recursion;

Functions, Procedures and Exception Handlers;

Communication and Synchronization

Page 2: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Iteration and Recursion

Iteration: Repetition of a sequence of instructions. Iteration is characterised by a set of initial

conditions, an iterative step and a termination condition ( http://www.hyperdictionary.com)

Basic iteration structures : The while statement, a pre-condition loop The do-while statement, a postcondition loop The for statement, a fixed-iteration loop

Page 3: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Pascal notation for iteration

while: i:=0;WHILE (i<5) DO

BEGINi:=i+1

END;

do while: i:=0;REPEAT

i:= i+1UNTIL i<0;

for: FOR i:=1 TO 5 DOj:=j+1;

Page 4: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Recursion

When a function calls itself, such a function is called "recursive".

If the call is via one or more other functions then this group of functions are called "mutually recursive”.

Any function that can be evaluated by a computer can be expressed in terms of recursive functions, without use of iteration, and conversely.

Every recursive process consists of two parts: A smallest, base case that is processed without recursion A general method that reduces a particular case to one or

more of the smaller cases, making progress toward eventually reducing the problem to the base case

Page 5: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Recursion vs. Iteration

For each recursive call, OS needs to keep track of the state of calling function (local variable, registers, return address) in the stack.

The size of stack depends on the depth of the recursion

In general, recursive program require more memory and time than iterative one.

Page 6: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Recursion vs. Iteration

Iteration:int factorial(int n) {

int count, ans = 1; for (count=1 ; count <= num; count++ )

ans *= count; return ans;

} Recursion

int factorial(int n) {if (n == 0 )

return 1;else

return n * factorial(n-1);

}

Page 7: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Wasteful example: Fibonacci Number Fo = 0, F1 = 1 Fn = F n-1+Fn-2 for n>=2 int Fibonacci(int){

if(n<=0)return 0;

else if (n==1)return 1;

elsereturn Fibonacci(n-1) + Fibonacci(n-2);

}

Page 8: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Tail Recursion

A special form of recursion where the last operation of a function is a recursive call to the function itself

In this case, as usual, local variables of the calling function will be pushed in stack and than restored after the recursive call returns. But they will be immediately discarded, because recursive call was the last action of the function. It is s wasteful to keep track of local variables of all previous instances of the function.

It is recommended to transform tail recursion into iteration Tail recursion could be transform to iteration by reassigning the calling parameters to the values specified in the recursive call, and branching to the beginning of the function

http://www.nist.gov/dads/HTML/tailrecursn.html http://www.cas.mcmaster.ca/~emil/se2c04/18recursion.pdf

Page 9: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Tail Recursion to Iteration The following finds the maximum value in a list.

Tail recursion : int max_list(list l, int max_so_far){if (null == l) {

return max_so_far;}if (max_so_far < head(l)) {

return max_list(tail(l), head(l));} else {

return max_list(tail(l), max_so_far);}

} Iteration: int max_list(list l, int max_so_far{

for (;;) {if (null == l) {

return max_so_far;}if (max_so_far < head(l)) {

max_so_far = head(l);l = tail(l);

} else {max_so_far = max_so_far;l = tail(l);

}}

}

Page 10: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Function, Procedures, Methods… Function is a named section of a program that

performs a specific task. Functions accept information in the form of arguments (the values that are passed through the function) and evaluate the arguments to provide results.

Some programming languages make a distinction between a function, which returns a value, and a procedure, which performs some operation but does not return a value.

Methods – in Object Oriented Programming, function of the class called methods

Page 11: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Exception Handling

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions (file not found, array index out of bound)

Traditional methods of exception handling: Return a status code with agreed-upon values

to indicate either success or failure. Assign an error code to a global variable and

have other functions examine it. Terminate the program.

Page 12: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Exception Handling

The Java and C++ provide a mechanism known as exceptions to help programs report and handle errors.

When an error occurs, the program throws an exception. It means that the normal flow of the program is interrupted and that the runtime environment attempts to find an exception handler--a block of code that can handle a particular type of error. The exception handler can attempt to recover from the error or, if it determines that the error is unrecoverable, provide a gentle exit from the program.

Page 13: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Exception Handling

Statements that play a part in handling exceptions: The try statement identifies a block of statements which we want

to monitor for errors. The catch statement must be associated with a try statement

and identifies a block of statements that can handle a particular type of exception. The statements are executed if an exception of a particular type occurs within the try block.

General form of these statements: try {

statement(s) }

catch (exceptiontype name) { statement(s)

}

Page 14: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Exception Handling

When an exception is thrown: the runtime mechanism first searches for an appropriate

handler in the current scope. If no such handler exists, control is transferred from the

current scope to a higher block in the calling chain. This process is iterative: It continues until an appropriate handler has been found.

At this point, the stack has been unwound and all the local objects that were constructed on the path from a try block to a throw expression have been destroyed.

In the absence of an appropriate handler, the program terminates.

http://www.informit.com/isapi/guide~cplusplus/seq_id~102/guide/content.asp

Page 15: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Communication and Synchronization(CS 440) Independent process cannot affect or be

affected by the execution of another process. Cooperating process can affect or be affected

by the execution of another process Concurrent execution of cooperating

processes requires mechanisms that allows processes to communicate with each other.

Page 16: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Means of Communication Pipes:

Pipe is a technique for passing information from one process to another. Pipe is one-way communication only. Basically, a pipe passes a parameter such as the output of one process to

another process which accepts it as input. The system temporarily holds the piped information until it is read by the

receiving process. For two-way communication between processes, two pipes can be set up,

one for each direction. Can be created from command line or within a C program. Processes using pipes must have a common parent process

Signals provide a simple method for transmitting software interrupt to UNIX

processes. Signals tend to be used for handling abnormal conditions rather than

transmission of data between processes. Process can deal with a signal in one of the following ways:

The process can let the default action happen The process can block the signal (some signals cannot be ignored) the process can catch the signal with a handler

Page 17: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Message passing system A process running on one processor may send a message to a

process running on the same processor or another. A common use of message passing is for communication in a

parallel computer. A message passing system provides primitives for sending and

receiving messages. These primitives may by either synchronous or asynchronous or both.

A synchronous send will not complete (will not allow the sender to proceed) until the receiving process has received the message.

An asynchronous send simply queues the message for transmission without waiting for it to be received (like posting a letter).

Messages may be sent to a named process or to a named mailbox which may be readable by one or many processes.

Messages may have a priority, allowing the receiver to read the highest priority messages first.

Page 18: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Means of Communication Sockets

The Unix mechansim for creating a virtual connection between processes.

Usually used in client-server communication They can be of two types, stream (bi-directional) or datagram (fixed

length destination-addressed messages). The socket library function socket() creates a communications end-point

or socket and returns a file descriptor with which to access that socket. The socket has associated with it a socket address, consisting of a port

number and the local host's network address.http://www.faqs.org/rfcs/rfc147.html - description of sockets

Shared memory Memory which can be access by more than one process in a

multitasking operating system with memory protection. Created by system call

Page 19: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Synchronization (CS 440, chapter 7) Concurrent access to shared data may result in data

inconsistency. Race condition:

The situation where several processes access and manipulate shared data concurrently. The final value of the shared data depends upon which process finishes last.

To prevent race conditions, concurrent processes must be synchronized.

The Critical-Section Problem: n processes all competing to use some shared data Each process has a code segment, called critical section, in

which the shared data is accessed. Problem – ensure that when one process is executing in its

critical section, no other process is allowed to execute in its critical section.

Page 20: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Means of synchronization

Bakery Algorithm Before entering its critical section, process

receives a number. Holder of the smallest number enters the critical section.

If processes Pi and Pj receive the same number, if i < j, then Pi is served first; else Pj is served first.

(See Operating System Concepts by Silberschatz, Galvin, Gagne; page 196 for actual implementation)

Page 21: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Semaphores The classic method for restricting access to shared resources in a multi-

processing environment Semaphores are created through system calls Semaphore has an internal integer counter which is preset to a given value

(usually the number of processes that should be allowed simultaneous access). This integer variable that can only be accessed via two indivisible (atomic)

operationswait (S):

while S 0{; // no-opS--;

}signal (S):

S++; Before entering a critical section, a process checks the status of the semaphore

counter. If the counter is positive, it is decremented by one, and the process allowed access. Otherwise, the process waits.

Likewise, a process already inside the critical section, before leaving the section sends a call to increment the counter by one.

Page 22: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Semaphores

Critical Section of n ProcessesShared data: semaphore mutex; initially

mutex = 1Code for each process Pi:

do { wait(mutex); critical section

signal(mutex); remainder section

} while (1);

Page 23: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Deadlocks

Deadlock – two or more processes are waiting indefinitely for an event that can be caused by only one of the waiting processes.

Deadlock can occur if following conditions are holds simultaneously: Mutual exclusion Hold and wait No preemption Circular wait

To prevent deadlock we ensure that at leas one of these conditions never holds

Page 24: Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.

Classic Problems of Synchronization Producer-Consumer Problem

Also called the bounded-buffer problem. A producer produces data that is consumed by a consumer. (e.g. spooler

and printer). A buffer holds the produced data which is not yet consumed. There exist

several producers and consumers Consumer must wait if the buffer is empty, producer must wait if the buffer is

full

The Readers-Writers Problem Several readers can read a data at the same time, but writer have to be

alone in critical section.

The Dining-Philosopher Problem N philosophers shares a common circular table with n chopsticks placed

between them. Each philosopher can eat if he pick up 2 chopstick. Task is to allocate a chopsticks in a deadlock-free manner