PPL Unit-4 Material
PPL Unit-4 Material
Encapsulation:
– Original motivation:
Obvious solution: a grouping of subprograms that are logically related into a unit that can be
separately compiled.
– These are called encapsulations
Definitions: An abstract data type is a user-defined datatype that satisfies the following two
conditions:
Definition 1: The representation of and operations of objects of the type are defined in a single
syntactic unit; also, other units can create objects of the type.
Definition 2: The representation of objects of the type is hidden from the program units that use
these objects, so the only operations possible are those provided in the type's definition.
– Unit level
– Program level
Because there are no language issues in instruction-and program-level concurrency, they are not
addressed here.
The Evolution of Multiprocessor Architectures:
1. Late 1950s-One general-purpose processor and one or more special-purpose processors for input
and output operations
➢ Early 1960s -Multiple complete processors, used for program-level concurrency.
– Single-Instruction Multiple-Data (SIMD) machine The same instruction goes to all processors,
each with different data -e.g., vector processors
Def: A thread of control: in a program is the sequence of program points reached as control flows
through the program.
Categories of Concurrency:
– Physical concurrency -Multiple independent processors ( multiple threads of control)
➢ When a program unit starts the execution of a task, it is not necessarily suspended
➢ When a task‘s execution is completed, control may not return to the caller
Def: A task isdisjointif it does not communicate with or affect the execution of any other task in the
program in any way Task communication is necessary for synchronization
– Task communication can be through:
➢ Parameters
➢ Message passing
– Kinds of synchronization:
➢ Cooperation
Task A must wait for task B to complete some specific activity before task A can continue its
execution
e.g., the producer-consumer problem
➢ Competition
When two or more tasks must use some resource that cannot be simultaneously used ., a shared
counter. A problembecause operations are not atomic
➢ Competition is usually provided by mutually exclusive access(methods are discussed later
➢ Providing synchronization requires a mechanism for delaying task execution
➢ Task execution control is maintained by a program called the scheduler, which maps task
execution onto available processors.
➢ Runnable or ready -ready to run but not currently running (no available processor)
➢ Running
➢ Blocked -has been running, but cannot not continue (usually waiting for some event to occur)
➢ Monitors
➢ Message Passing
– Semaphores can be used to implement guards on the code that accesses shared data structures
– Semaphores have only two operations, wait and release (originally called Pand V by Dijkstra)
– Semaphores can be used to provide both competition and cooperation synchronization
– DEPOSIT must first check empty spots to see if there is room in the buffer
– If there is room, the counter of empty spots is decremented and the value is inserted
– The operations of FETCH and DEPOSIT on the semaphores are accomplished through two
semaphore operations named wait and release wait (aSemaphore)
if a Semaphore‘s counter > 0 thenDecrement aSemaphore‘s counter else
Put the caller in aSemaphore‘s queue Attempt to transfer control to some ready task (If the task ready
queue is empty, deadlock occurs) end
release(aSemaphore)
if aSemaphore‘s queue is empty then Increment aSemaphore‘s counter
else
Put the calling task in the task ready queue Transfer control to a task from aSemaphore‘s queue
end
– Competition Synchronization with Semaphores:
– Misuse of semaphores can cause failures in competition synchronization e.g., The program will
deadlock if the release of access is left out.
➢ Concurrent Pascal isPascal + classes, processes (tasks), monitors, and the queue data type (for
semaphores)
Example language: Concurrent Pascal (continued) processes are types Instances are
staticallycreated by declarations
➢ An instance is ―started‖ by init, which allocateits local data and begins its execution
type some_name = monitor (formal parameters) shared variables , local procedures exported
procedures (have entry in definition) initialization code
Competition Synchronization with Monitors:
– Access to the shared data in the monitor is limited by the implementation to a single process at a
time; therefore, mutually exclusive access is inherent in the semantic definition of the monitor
– Multiple calls are queued
Java Threads
The concurrent units in Java are methods named run
–A run method code can be in concurrent execution with other such methods
–The process in which the run methods execute is called athread
Class myThread extends Thread public void run () {…}
}
…
Thread myTh = new MyThread (); myTh.start();
Thread Priorities
– A thread‗s default priority is the same as the thread that create it .
– If main creates a thread, its default priority is NORM_PRIORITY
– The notify method is called to tell one waiting thread that the event it was waiting has happened
– The notifyAll method awakens all of the threads on the object‗s wait list
C# Threads
EXCEPTION HANDLING
Exception: A run-time error conditions
In a language without exception handling:
When an exception occurs, control goes to the operating system, where a message is displayed and
the program is terminated
In a language with exception handling:
Programs are allowed to trap some exceptions, thereby providing the possibility of fixing the
problem and continuing. Many languages allow programs to trap input/ output errors (including
EOF)
A language that does not have exception handling capabilities can still define, detect, raise, and
handle exceptions.
– Alternatives:
➢ Send an auxiliary parameter or use the return value to indicate the return status of a Subprogram
➢ e.g., C standard library functions
➢ Pass a label parameter to all subprograms (error return is to the passed label)
➢ e.g., FORTRAN
➢ Pass an exception handling subprogram to all subprograms
– Where does execution continue, if at all, after an exception handler completes its execution?
– Should there be default exception handlers for programs that do not provide their own?
exception_choice form:
exception_name | others
– Reserved word others
Indicate, it can handle any
exceptions
• Handlers are grouped together in an exception clause
• Handlers are placed at the end of the block or unit in which they occur
begin
-- the block or unit body --
exception
when exception_name1 =>
-- first handler --
when exception_name2 =>
-- second handler --
-- other handlers --
end;
Continuation
• The block or unit that raises an exception but does not handle it is always terminated (also any
block or unit to which it is propagated that does not handle it is always terminated)
• Control never returns to the raising block or unit after the exception is handled as per the
requirements specification of Ada.
• However, in case of a block, if the statement that raises the exception and the block that handles
it are in the same block, that statement can be retried its execution…
Predefined Exceptions
Exception that are defined in default package called standard
• CONSTRAINT_ERROR - index constraints, range constraints, etc. ex: array subscript out of
range
• NUMERIC_ERROR - numeric operation cannot return a correct value (overflow, division by
zero, etc.)
• PROGRAM_ERROR - call to a subprogram whose body has not been elaborated
• STORAGE_ERROR - system runs out of heap
• TASKING_ERROR - an error associated with tasks
Each of these is actually a category of exceptions
-- handler code
}
...
-- handler code
Continuation
• If no handler is found in the try construct, the search is continued in the nearest enclosing try
construct, etc.
• If no handler is found in the method, the exception is propagated to the method’s caller
• If no handler is found (all the way to main method), the program is terminated
• To ensure that all exceptions are caught, a handler can be included in any try construct that
catches all exceptions
– Simply use an Exception class parameter
Of course, it must be the last in the try construct
Checked and Unchecked Exceptions
• Exceptions of class Error and RunTimeException and all their descendants are called
unchecked exceptions; all other exceptions are called checked exceptions.
• Unchecked Exceptions are never a concern of the compiler, and any method can throw them.
These are handled by JVM.
• Compiler ensures that all Checked exceptions that may be thrown by a method must be
either:
– Listed in the throws clause, or
– Handled in the method
The finally Clause
. . .
catch (. . .) {
. . .
finally {
. . .
}
LOGIC PROGRAM PARADIGM:
Based on logic and declarative programming 60‘s and early 70‘s, Prolog (Programming in logic,
1972) is the most well known representative of the paradigm.
– Prolog is based on Horn clauses and SLD resolution
– Specially designed for theorem proof and artificial intelligence but allows general purpose
computation.
– Some other languages in paradigm: ALF, Frill,G¨odel,, Mercury, Oz, Ciao, _Prolog, datalog, and
CLP languages
Prolog terms:
Atoms:
– 1 Strings with starting with a small letter and consist of o [a-zA-Z 0-9]*
o a aDAM a1 2
– Numbers
Variables:
– Strings with starting with a capital letter or and consist of
[a-zA-Z 0-9]*
– Adam adam A093
– is the universal match symbol. Not variable
Structures:
Starts with an atom head have one or more arguments (any term) enclosed in parenthesis, separated
by comma structure head cannot be a variable or anything other than atom.
a(b) a(b,c) a(b,c,d) ++(12) +(*) *(1,a(b)) ‘hello world‘(1,2) p X(b) 4(b,c) a() ++() (3) × some
structures defined as infix:
+(1,2) _ 1+2 , :-(a,b,c,d) _ a :-b,c,d Is(X,+(Y,1)) _ X is X + 1
Static sugars:
Prolog interpreter automatically maps some easy to read syntax into its actual structure. List: [a,b,c] _
.(a,.(b,.(c,[])))
Head and Tail: [H|T] _ .(H,T)
String: "ABC" _ [65,66,67] (ascii integer values) use display (Term). to see actual structure of the
term
Unification:
Bi-directional (both actual and formal argument can be instantiated).
1. if S and T are atoms or number, unification successful only if S = T
2. if S is a variable, S is instantiated as T, if it is compatible with current constraint store (S
isinstantiated to another term, they are unified)
3. if S and T are structures, successful if: head of S = head of Tthey have same arityunification of all
corressponding terms are successful.
Declarations:
Two types of clauses:
p1(arg1, arg2, ...) :-p2(args,...) , p3(args,...) .means if p2 and p3 true, then p1 is true. There can be
arbitrary number of (conjunction of) predicates at right hand side.
p(arg1, arg2, ...) .sometimes called a fact. It is equivalentto: p(arg1, arg2, ...) :-true. p(args) :-q(args) ;
s(args) .
Is disjunction of predicates. q or s implies p. Equivalent to: p(args) :-q(args). p(args) :-s(args).
A prolog program is just a group of such clauses.
Lists Example:
– list membership memb(X, [X| Re s t ]) . memb(X, [ | Re s t ]) :-memb(X, Re s t ).
– second list contains first list Sublist (L1,L2) :-prefix of (L1,L2). Sublist (L,[|R]):-sublist(L,R).
Procedural Interpretation:
For goal clause all matching head clauses (LHS of clauses) arekept as backtracking points (like a
junction in maze search) Starts from first match. To prove head predicate, RHS predicates need to be
proved recursively. If all RHS predicates are proven, head predicate is proven. When fails, prolog
goes back to last backtracking point and tries next choice. When no backtracking point is left, goal
clause fails. All predicate matches go through unification so goal clause variables can be instantiated.
Deficiencies of Prolog:
➢ Resolution order control
➢ The closed-world assumption
➢ The negation problem
➢ Intrinsic limitations
Applications of Logic Programming
➢ Relational database management systems
➢ Expert systems
➢ Natural language processing