21
May 6, 2004 1 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko Programming Languages Programming Languages (ICE 1341) (ICE 1341) Lecture #19 Lecture #19 May 7, 2004 In-Young Ko iko .AT. i cu . ac.kr Information and Communications University (ICU)

May 6, 2004 1 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko Programming Languages (ICE 1341) Lecture #19 Programming Languages (ICE 1341)

Embed Size (px)

Citation preview

May 6, 2004 1 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

Programming LanguagesProgramming Languages(ICE 1341)(ICE 1341)

Lecture #19Lecture #19 May 7, 2004

In-Young Koiko .AT. icu.ac.kr

Information and Communications University (ICU)

May 6, 2004 2 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

AnnouncementsAnnouncements

The The scores of the homework #4scores of the homework #4 are accessible are accessible from the class websitefrom the class website

The The grading policy of the homework #4grading policy of the homework #4 can be can be accessed via the class BBSaccessed via the class BBS

For the final project, you may need to For the final project, you may need to revise your revise your programming-languageprogramming-language design if: design if: Your language doesn’t support the Your language doesn’t support the full language full language

featuresfeatures (variable declarations, arithmetic/logical (variable declarations, arithmetic/logical operations, assignment, branching, iteration and block operations, assignment, branching, iteration and block definitions)definitions)

Your Your XML syntax is not complete or too complexXML syntax is not complete or too complex to use to use

May 6, 2004 3 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

Review of the Previous LecturesReview of the Previous Lectures

Object-oriented Programming Concepts and Object-oriented Programming Concepts and DefinitionsDefinitions

Overriden MethodsOverriden Methods Abstract Classes and MethodsAbstract Classes and Methods Design Issues for OOPLsDesign Issues for OOPLs

Exclusive use of objects in typing systemsExclusive use of objects in typing systems Subclsses as subtypesSubclsses as subtypes Polymorphism and dynamic type checkingPolymorphism and dynamic type checking Multiple inheritanceMultiple inheritance Object allocation and deallocation mechanismsObject allocation and deallocation mechanisms

Object-oriented Processing of XML DataObject-oriented Processing of XML Data

May 6, 2004 4 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

Smalltalk – CharacteristicsSmalltalk – Characteristics

The 1The 1stst language to include complete support language to include complete support for the object-oriented programming paradigmfor the object-oriented programming paradigm

Everything is an objectEverything is an object All bindingAll binding of messages to methods is of messages to methods is dynamicdynamic Because all variables are typeless, Because all variables are typeless, methods are methods are

all polymorphicall polymorphic All subclasses are subtypesAll subclasses are subtypes No multiple inheritanceNo multiple inheritance

May 6, 2004 5 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

Smalltalk – EvaluationSmalltalk – Evaluation

The syntax of the language is The syntax of the language is simple and simple and regularregular

SlowSlow compared with conventional compiled compared with conventional compiled imperative languagesimperative languages

Dynamic binding Dynamic binding allows type errors to go allows type errors to go undetectedundetected until run time until run time

Greatest impact: advancement of OOPGreatest impact: advancement of OOP

May 6, 2004 6 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

C++ – CharacteristicsC++ – Characteristics

A hybrid language: procedural + OOPA hybrid language: procedural + OOP Access controlsAccess controls for members for members::

PrivatePrivate: : visible only in the class and friendsvisible only in the class and friends ProtectedProtected: : visible in the class and in subclasses, visible in the class and in subclasses,

but not clientsbut not clients PublicPublic: : visible in subclasses and clientsvisible in subclasses and clients

DDisallows subclasses from being subtypesisallows subclasses from being subtypes InheritanceInheritance

Private derivationPrivate derivation –– inherited inherited public and protected public and protected members are private in the subclassesmembers are private in the subclasses

Public derivationPublic derivation – – publicpublic and protected members and protected members are also public and protected in subclassesare also public and protected in subclasses

May 6, 2004 7 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

C++ – Private & Public DerivationsC++ – Private & Public Derivations

class base_class {class base_class { privateprivate:: int int aa;; float float xx;; protectedprotected:: int int bb;; float float yy;; publicpublic:: int int cc;; float float zz;;};};

class subclass_1 : class subclass_1 : publicpublic base_class { base_class { // In this, // In this, bb and and yy are are protectedprotected and and cc and and zz are are publicpublic};};

class subclass_2 : class subclass_2 : privateprivate base_class { base_class { // In this, // In this, bb, , yy, , cc, and , and zz are are privateprivate, and no derived class , and no derived class // // has access to any member of base_classhas access to any member of base_class};};

* AW Lecture Notes

May 6, 2004 8 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

C++ – ReexportationC++ – Reexportation

A member that is not accessible in a subclass (because A member that is not accessible in a subclass (because of private derivation) can be declared to be visible there of private derivation) can be declared to be visible there using the using the scope resolution operatorscope resolution operator ( (::::))

e.g., e.g., class subclass_3 : class subclass_3 : privateprivate base_class { base_class { base_class :: cbase_class :: c;; …… }}

MMotivation for using otivation for using private derivationprivate derivation:: a derived class a derived class adds some new members, but adds some new members, but does not want its clients does not want its clients to see the members of the parent classto see the members of the parent class, even though , even though they had to be public in the parent class definitionthey had to be public in the parent class definition

* AW Lecture Notes

May 6, 2004 9 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

C++ – Multiple InheritanceC++ – Multiple Inheritance

If there are two inherited members with the If there are two inherited members with the same name, they can both be reference using same name, they can both be reference using the the scope resolution operatorscope resolution operator

class class AA { { public:public: intint nn;; floatfloat ff;;};};

class class BB { { public:public: intint nn;; char char cc;;};};

class class CC : public : public AA, public , public BB {{ … … ff = 10.23; = 10.23; cc = ‘$’; = ‘$’; A::nA::n = 10; = 10; B::nB::n = 20; = 20;};};

May 6, 2004 10 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

C++ – Dynamic BindingC++ – Dynamic Binding

VVirtualirtual method: a method method: a method thatthat can be can be called through called through polymorphic variablespolymorphic variables and and dynamically bound to dynamically bound to messagesmessages

public class public class shapeshape { { public: public: virtualvirtual void void draw() = 0draw() = 0; …; …}}public class public class circlecircle : public : public shapeshape { { public: public: virtualvirtual void void draw() draw() { … } …{ … } …}}public class public class rectanglerectangle : public : public shapeshape { { public: public: virtualvirtual void void draw()draw() { … } … { … } …}}public class public class squaresquare : public : public rectanglerectangle { { public: public: virtualvirtual void void draw()draw() { … } … { … } …}}……square s; rectangle r;square s; rectangle r;shape &ref_shape = s; shape &ref_shape = s; ref_shape.ref_shape.draw();draw();r.r.draw();draw();

DDynamically boundynamically bound to to drawdraw in in squaresquare

DDynamically boundynamically bound to to drawdraw in in rectanglerectangle

Pure virtual functionPure virtual function

May 6, 2004 11 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

Java – CharacteristicsJava – Characteristics

All data are objects except the primitive typesAll data are objects except the primitive types All primitive types have All primitive types have wrapper classeswrapper classes that that

store one data valuestore one data value (e.g., (e.g., new Integer(10)new Integer(10))) All objects are All objects are heap-dynamicheap-dynamic, are referenced , are referenced

through reference variables, and most are through reference variables, and most are allocated with allocated with newnew

Single inheritance onlySingle inheritance only, but , but interfacesinterfaces provide provide a a version of version of multiple inheritancemultiple inheritance

Methods can be Methods can be finalfinal (cannot be overriden) (cannot be overriden) AAll messages are dynamically bound to ll messages are dynamically bound to

methodsmethods, unless the method is , unless the method is finalfinal

May 6, 2004 12 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

Implementing OO ConstructsImplementing OO Constructs

Class Instance Record (CIR)Class Instance Record (CIR): A storage structure : A storage structure for the for the instance variablesinstance variables of class instances of class instances

Virtual Method Table (VMT)Virtual Method Table (VMT): A storage structure : A storage structure for the for the list of dynamically bound methodslist of dynamically bound methods that can that can be called from an instance of a classbe called from an instance of a class

public class public class AA { { public int public int aa, , bb;; public void public void draw()draw() { … } { … } public int public int area()area() { … } { … }}}Public class Public class BB extends A { extends A { public int public int cc, , dd;; public void public void draw()draw() { … } { … } public void public void sift()sift() { … } { … }}}

vtable pointervtable pointer

aa

bb

cc

dd

CIR for BCIR for B VMT for BVMT for B

A’s A’s areaarea

B’s B’s drawdraw

B’s B’s siftsift

May 6, 2004 13 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

ConcurrencyConcurrency

““A program is said to be A program is said to be concurrentconcurrent if it contains if it contains more than one active execution contextmore than one active execution context” ” [M. Scott][M. Scott]

vvoid oid concurrentPrintconcurrentPrint() {() {

(new Thread () {(new Thread () { public void run() {public void run() { while (true) {while (true) { try {try { System.out.print("A");System.out.print("A"); sleep(sleep(0,0,1);1); } catch (Exception e) { }} catch (Exception e) { } }} }).start();}).start();

(new Thread () {(new Thread () { public void run() {public void run() { while (true) {while (true) { try {try { System.out.print("B");System.out.print("B"); sleep(0sleep(0,1,1);); } catch (Exception e) { }} catch (Exception e) { } }} }).start();}).start();}} Java

Forking two concurrent Forking two concurrent execution threadsexecution threads

Main Program ControlMain Program Control

Printing “A”Printing “A” Printing “B”Printing “B”

May 6, 2004 14 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

Categories of ConcurrencyCategories of Concurrency

TThread of controlhread of control: A: A sequence of program sequence of program points reached as control flows through the points reached as control flows through the programprogram

Categories of Concurrency:Categories of Concurrency: Physical concurrencyPhysical concurrency: Concurrency supported: Concurrency supported

mmultiple independent processorultiple independent processorss Logical concurrencyLogical concurrency:: CConcurrency presented by oncurrency presented by

time-sharing one processortime-sharing one processor (software can be (software can be designed as if there were multiple threads of control) designed as if there were multiple threads of control)

Coroutines provide only Coroutines provide only quasi-concurrencyquasi-concurrency

* AW Lecture Notes

May 6, 2004 15 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

Subprogram-Level ConcurrencySubprogram-Level Concurrency (1) (1)

TTask ask (P(Processrocess)):: AA program unit that can be in program unit that can be in concurrent execution with other program unitsconcurrent execution with other program units

Tasks differ from ordinary Tasks differ from ordinary subprograms in that:subprograms in that: A task may be A task may be implicitly startedimplicitly started When a program unit starts the When a program unit starts the

execution of a task, the execution of a task, the program is not necessarily program is not necessarily suspendedsuspended

When a task’s execution is When a task’s execution is completed, completed, control may not control may not return to the callerreturn to the caller

vvoid oid concurrentPrintconcurrentPrint() {() {

(new Thread () {(new Thread () { public void run() {public void run() { while (true) {while (true) { try {try { System.out.print("A");System.out.print("A"); } catch (Exception e) { }} catch (Exception e) { } }} }).start();}).start();

(new Thread () {(new Thread () { public void run() {public void run() { while (true) {while (true) { try {try { System.out.print("B");System.out.print("B"); } catch (Exception e) { }} catch (Exception e) { } }} }).start();}).start();}}

May 6, 2004 16 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

Subprogram-Level ConcurrencySubprogram-Level Concurrency (2) (2)

A task is A task is disjointdisjoint if it does not if it does not communicate with or affect the communicate with or affect the execution of any other task in execution of any other task in the program in any way the program in any way

Task communication is Task communication is necessary for necessary for synchronizationsynchronization Shared nonlocal variablesShared nonlocal variables ParametersParameters Message passingMessage passing

Race ConditionRace Condition: a situation in : a situation in which more than one tasks are which more than one tasks are racing to use shared resourcesracing to use shared resources

int int countcount = 0; = 0;vvoid oid concurrentPrintconcurrentPrint() {() {

(new Thread () {(new Thread () { public void run() {public void run() { try {try { while ( while (countcount++ < 20) {++ < 20) {

System.out.print("A");System.out.print("A"); sleep(0sleep(0, 1, 1););

}} } catch (Exception e) { }} catch (Exception e) { } }} }).start();}).start();

(new Thread () {(new Thread () { public void run() {public void run() { try {try { while ( while (countcount++ < 20) {++ < 20) {

System.out.print("B");System.out.print("B"); sleep(0sleep(0, 1, 1););

}} } catch (Exception e) { }} catch (Exception e) { } }} }).start();}).start();}}

May 6, 2004 17 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

Semaphores – Dijkstra 1965Semaphores – Dijkstra 1965class Semaphore {class Semaphore { int s = 0;int s = 0; public synchronized void public synchronized void p()p() {{ while (while (ss < 0) continue; < 0) continue; ss--;--; }} public synchronized void public synchronized void v()v() { { ss++;++; }}}}

int int countcount = 0; = 0;Semaphore Semaphore semsem = new Semaphore(); = new Semaphore();

vvoid oid concurrentPrintconcurrentPrint() {() {

(new Thread () {(new Thread () { public void run() {public void run() { try {try { while (true) { while (true) { sem.p();sem.p(); // wait // wait if (if (countcount++ >= 20) { ++ >= 20) { v(semaphore);v(semaphore); break; } break; } sem.v(); sem.v(); // release // release System.out.print("A");System.out.print("A"); sleep(0sleep(0, 1, 1);); } } } catch (Exception e) { }} catch (Exception e) { } }} }).start();}).start();

(new Thread () {(new Thread () { public void run() {public void run() { try {try {while (true) {while (true) { sem.p();sem.p(); // wait // wait if (if (countcount++ >= 20) { ++ >= 20) { v(semaphore);v(semaphore); break; } break; } sem.v();sem.v(); // release // release System.out.print(“System.out.print(“BB");"); sleep(0sleep(0, 1, 1);); }} } catch (Exception e) { } } catch (Exception e) { } }} }).start();}).start();}}

SSemaphoreemaphore:: a data a data structure consisting of a structure consisting of a countercounter and and a queue for a queue for storing task descriptorsstoring task descriptors

Guarded codeGuarded code

May 6, 2004 18 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

Synchronization ProblemsSynchronization Problems

Cooperation SynchronizationCooperation Synchronization: synchronization in : synchronization in counting somethingcounting something

e.g., The previous example of sharing a counter, e.g., The previous example of sharing a counter, Sharing a buffer by a producer and a consumerSharing a buffer by a producer and a consumer

Competition SynchronizationCompetition Synchronization: synchronization in : synchronization in sharing a resourcesharing a resource

e.g., Dining Philosophers probleme.g., Dining Philosophers problem

Peterson & Silberschatz

May 6, 2004 19 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

Dining Philosophers ProblemDining Philosophers Problem

Peterson & Silberschatz

Five philosophersFive philosophers spend spend their lives thinking and eatingtheir lives thinking and eating

The philosophers The philosophers share a share a circular tablecircular table

In the center of the table, In the center of the table, there is there is a bowl of ricea bowl of rice

The table is laid with The table is laid with five five chopstickschopsticks

When a philosopher gets When a philosopher gets hungry, he hungry, he tries to pickup tries to pickup two chopstickstwo chopsticks that are that are closest to himclosest to him

Dijstra 1965Dijstra 1965

May 6, 2004 20 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

Solving The Dining Philosophers Solving The Dining Philosophers Problem Using SemaphoresProblem Using Semaphores

Peterson & Silberschatz

Semaphore[] Semaphore[] chopsticks = new Semaphore[5]chopsticks = new Semaphore[5];;chopsticks[0] = new Semaphore();chopsticks[0] = new Semaphore();……while (true) {while (true) { chopsticks[i].chopsticks[i].p()p();; chopsticks[(i+1) % 5].chopsticks[(i+1) % 5].p()p();;

……// eat// eat……

chopsticks[i].chopsticks[i].v()v();; chopsticks[(i+1) % 5].chopsticks[(i+1) % 5].v()v();;

……// think// think……

}}

00

11

22

33

44

00

11

22 33

44

May 6, 2004 21 ICE 1341 – Programming Languages (Lecture #19) In-Young Ko

Evaluation of SemaphoresEvaluation of Semaphores

Misuse of semaphores Misuse of semaphores ((when a P operation is when a P operation is left outleft out) ) can cause can cause failures in cooperation failures in cooperation synchronizationsynchronization

e.g., e.g., out of index, out of index, buffer overflowbuffer overflow

Misuse of semaphores Misuse of semaphores ((when a V operation is when a V operation is left outleft out) ) can cause can cause failures in competition failures in competition synchronizationsynchronization

e.g., e.g., infinite loop, infinite loop, deadlockdeadlock