You are on page 1of 48

Advances in OS Lab Programs

1. Design, develop and execute a program using any thread library to create the number of threads specified by the user; each thread independently generates a random integer as an upper limit, and then computes and prints the number of primes less than or equal to that upper limit along with that upper limit.
IN !"D#$ I"N A process defines a Customized Computations framework in which a program executes. In traditiona operating s!stem the basic unit of CP" uti ization is a process. #ach process has its own program counter$ its own register states$ its own stack$ and its own address space. %ow a da!s$ in operating s!stem $ the basic unit of CP" uti ization is thread and a process ma! consist of one or more threads. &he thread is the part of the process that keeps track of code execution within that framework. #ach thread of a process has its own program counter$ its own register states$ and its own stack. 'ut a the threads of a process share the same address space. &hreads share a CP" in the same wa! as process do. On a mu tiprocessor threads run in a (uasi)para e $ whereas on a s shared memor! mu tiprocessor man! threads can run simu taneous !. Like process$ threads can create chi d threads$ can b ock waiting for s!stem ca s to comp ete$ and can change states during their course of execution. &hreads are referred to as ight weight process and process as heav!weight process. &hreads can improve app ication performance through para e ism As an ana og!$ the modern process is ike a studio$ and the thread is ike a musician who uses the studio to make music.

%!"$&'' (ND %!"$&'' $"N !") *)"$+

*ept. of CS#$ AI&$ 'anga ore

,-++)+,

Advances in OS Lab Programs A process is a program in execution or an instance of a program running on a computer. &wo essentia e ements of process are program code and a set of data associated with that code. At an! given point of time whi e the program is executing$ the process can be uni(ue ! characterized b! a number of e ements inc uding the fo owing$ Identifier. a uni(ue identifier associated with the process$ to distinguish it from a other process. 'tate, if the process is current ! executing it space is in the running state %riority, priorit! eve re ative to other processes. %rogram counter. the address of the next instruction in the program to be executed. -emory pointers. inc udes pointers to the program court and data associated with the process p us an! memor! b ocks shared with other processes. $ontext data. these are the data that are presenting registers in the processor whi e the process is executing. I." status information. inc udes outstanding I/O re(uests$ I/O devices0 assigned to the process$ ist of fi es in use b! process and so on. (ccounting Information, 1a! inc ude the amount of processor time and c ock time used$ time imits$ account numbers and so on.

&he information in the proceeding ist is stored in a data structure$ t!pica ! ca ed a process contro b ock that is created and managed b! the OS. &he process contro b ock is that it contains sufficient information so that it is possib e to interrupt a running process and ater resume execution as if the interruption had not occurred. &he process contro b ock is the ke! too that enab es the OS to support mu tip e processes and to provide for mu tiprocessing. 2hen process is interrupted the current va ues of the program counter and the processor registers are saved in the appropriate fie ds of the corresponding *ept. of CS#$ AI&$ 'anga ore , ,-++)+,

Advances in OS Lab Programs process contro b ock and state of process is changed to some other va ue$ such as b ocked or read!. &he OS is now free to support to some other process in the running state. &he program counter and context data for this purpose are oaded into the processor register and this process now begins to execute. %rocess 'tate &he behavior of an individua process can be characterized b! isting the se(uence of instruction that execute for that process. Such isting is referred to as a trace of process. A sma dispatcher program is there that switches the process from one process to another. A process can be in an! of the five states whi e it is on the s!stem. !#NNIN/, &he process that is current ! being executed. At most one process at a time can be in this state. !&(D0, A process that is prepared to execute when given the opportunit!. *)"$+&D.1(I IN/, A process that cannot execute unti some event occurs$ such as the comp etion of an I/O operation. N&1,A process that has 3ust been created but has not been admitted to the poo of executab e processes b! the OS$ &!pica !$ a new process has not !et been oaded into main memor!$ a though its process contro b ock has been created. &2I , A process that has been re eased from the poo of executab e processes b! the OS$ either because it ha ted or because it aborted for some reason.

&he %#2 and #4I& states are usefu constructs for process management. &he %ew state corresponds to a process that has 3ust been defined. &he OS can define a new process into two stages. 5irst$ the OS performs the necessar! housekeeping chores. An identifier is

*ept. of CS#$ AI&$ 'anga ore

,-++)+,

Advances in OS Lab Programs associated with the process. A tab e wi be needed to manage the process$ when it is a ocated and bui t. At this point$ the process is in the %#2 state. &his means that the OS has performed the necessar! actions to create the process but has not committed itse f to the execution of the process. 2hi e$ a process is in the %#2 state$ information concerning the process that is needed b! the OS is maintained in contro tab es in main memor!. 7owever$ the process itse f is not main memor!. &hat is the code of the program to be executed is not in main memor!$ and no space is a ocated for the data associated with that program. 2hi e$ the process is in the %#2 state$ the program remains in secondar! storage$ t!pica ! disk storage. A process exits a s!stem in two stages. 5irst a process is terminated when it reaches a natura comp etion point$ when it aborts due to an unrecoverab e error$ or when another process with the appropriate authorit! causes the process to abort. &ermination moves the process to #xit state. At this point$ the process is no onger e igib e for execution. &he tab es and other information associated with the 3ob are temporari ! preserved b! the OS$ which provides time for auxi iar! or support program to extract an! needed information. &he t!pe of events that eads to the each state transition for a process8 the possib e transaction are as fo ows. N#)) 34N&1, ( new process is executed to execute a program. N&1 34 !&(D0, he OS wi move a process from the new state to the 9ead! state when it is prepared to take on an additiona process. 1ost s!stem set some imit based on the number of existing process or the amount of virtua memor! committed to exiting processes. !&(D034!#NNIN/, 2hen it is time to se ect a process to run$ the OS chooses one of the process running is in the 9ead! state. &his is the 3ob of schedu er or dispatcher. !#NNIN/34&2I , &he current ! running process is terminated b! the OS if the process to indicate that it has comp eted or if it aborts. !#NNIN/34!&(D0, &he most common reason for this transition is that the 9unning process has reached the maximum a owab e time for uninterrupted execution8 virtua ! a mu tiprogramming operating s!stem impose this t!pe of time discip ine. !#NNIN/34*)"$+&D, A process is put in the ' ocked state if it re(uests something for which it must wait. A re(uest for OS is usua ! of the form of a s!stem service ca $

*ept. of CS#$ AI&$ 'anga ore

,-++)+,

Advances in OS Lab Programs that is a ca s!stem. *)"$+&D34!&(D0, A process in the ' ocked state is moved to the 9ead! state when the event for which it has been waiting for. !&(D034&2I , In some s!stems$ a parent ma! terminate a chi d process at an! time. A so$ if a parent terminates a terminated. chi d process associated with that parent ma! be from the running program to a procedure that is apart of the operating

5!&(D' A thread is a basic unit of CP" uti ization8 it comprises a thread I*$ a program counter$ a register set$ and a stack. It shares with other threads be onging to the same process its code section$ data section$ and other operating)s!stem resources$ such as open fi es and signa s. &here are two t!pes of threads one of which is sing e thread and other

*ept. of CS#$ AI&$ 'anga ore

,-++)+,

Advances in OS Lab Programs mu ti thread. A traditiona process has a sing e thread of contro . If a process has mu tip e threads of contro $ it can perform more than one task at a time. &he difference between a sing e)threaded process and mu ti)threaded process is shown in figure be ow.

Registers Code

Data

Stack Files

Register Code Stack

Register Data Stack

Register Files Stack

Sing e)threaded process

1u ti)threaded process

In certain situations$ a sing e app ication ma! be re(uired to perform severa simi ar tasks. 5or examp e$ a web server accepts c ient re(uests for web pages$ images$ sound and so forth. A bus! web server ma! have severa of c ients concurrent ! accessing it. If the web server ran as a traditiona sing e)threaded process$ it wou d be ab e to service on ! one c ient at a time. One so ution is to have the server run as a sing e process that accepts re(uests. 2hen the server receives a re(uest$ it creates a separate process to service that re(uest. In fact$ this process)creation method was in common use before threads became popu ar. &hreads p a! a vita ro e in remote procedure ca <9PC= s!stems. &he 9PCs a ow interprocess communication mechanism simi ar to ordinar! function or procedure ca s. 9PC servers are mu tithreaded. 5ina !$ man! operating s!stem kerne s are now mu tithreaded8 severa threads operate in the kerne $ and each thread performs a specific task$ such as managing devices or interrupt hand ing. 5or examp e$ So aris creates a set of threads in the kerne specifica ! for interrupt hand ing. *enefits &he benefits of mu tithreaded programming can be broken down into four ma3or categories.

*ept. of CS#$ AI&$ 'anga ore

>

,-++)+,

Advances in OS Lab Programs +. ,. 6. :. 9esponsiveness 9esource sharing #conom! "ti ization of mu tiprocessor architectures

!esponsiveness , 1u tithreading an interactive app ication ma! a ow a program to continue running even if part of it is b ocked or is performing a ength! operation$ thereb! increasing responsiveness to the user. !esource sharing, &hreads share the memor! and the resources of the process to which the! be ong. &he benefit of sharing code and data is that it a ows an app ication to have severa different threads of activit! within the same address space. &conomy, A ocating memor! and resources for process creation is cost !. 'ecause threads share resources of the process to which the! be ong$ it is more economica to create and context)switch threads. In genera it is much more time consuming to create and manage process than threads. #tili6ation of multiprocessor architectures, &he benefits of mu tithreading can be great ! increased in a mu tiprocessor architecture$ where threads ma! be running in para e on different processors. A sing e)threaded process can on ! run on CP"$ no matter how man! are avai ab e. -ultithreading -odels &hreads support at user eve $ for user threads$ or b! the kerne $ for 7ernel threads. "ser threads are supported above the kerne and are managed without kerne support$ whereas kerne threads are supported and managed direct ! b! the operating s!stem. -any3to3"ne -odel &he man!)to)one mode maps man! user) eve threads to one kerne thread. &hread management is done b! the thread ibrar! in user space$ so it is efficient$ but the entire process wi b ock if a thread makes a b ocking s!stem ca . 5igure shows man!)to) One mode .

*ept. of CS#$ AI&$ 'anga ore

,-++)+,

Advances in OS Lab Programs "ne3to3"ne -odel &he one)to)one mode maps each user thread to a kerne thread. It provides more concurrenc! than the man!)to)one mode b! a owing another thread to run when a thread makes a b ocking s!stem ca . It a so a ows mu tip e threads to run in para e on mu tiprocessors. &he on ! drawback to this mode is that creating a user thread re(uires creating the corresponding kerne thread. 5igure shows One)to)One mode

-any3to3-any -odel &he 1an!)to)1an! mode mu tip exes man! user) eve threads to a sma er or e(ua number of kerne s threads. &he number of kerne threads ma! be specific to either a particu ar app ication or a particu ar machine. 2hereas the man!)to)one mode a ows the deve oper to create as man! user threads as the! wishes$ because the kerne can schedu e on ! one thread at a time. &he man!)to)man! mode suffers from neither of these shortcomings. *eve opers can create as man! user threads as necessar! and corresponding kerne thread can run in para e on a mu tiprocessor.

hread libraries &hread ibrar! provides the programmer an API for creating and managing threads. &here are two primar! wa!s of imp ementing a thread ibrar!. &he first approach is to provide a ibrar! entire ! in user space with no kerne support. A code and data structures for the ibrar! exist in user space.

*ept. of CS#$ AI&$ 'anga ore

,-++)+,

Advances in OS Lab Programs &he second approach is to imp ement a kerne ) eve ibrar! supported direct ! b! the operating s!stem. In this case$ code and data structures for the ibrar! exist in kerne space. &hree main thread ibraries are used$ the! are

POSI4 Pthreads 2in6, Aava

&he POSI4 standard ma! be provided as either a user or kerne ) eve ibrar!. &he 2in6, thread ibrar! is a kerne ) eve ibrar! avai ab e on 2indows s!stems. &he Aava thread API a ows thread creation and management direct ! in Aava programs. &he AB1 is running on top of a host operating s!stem. &he Aava thread API is t!pica ! imp emented using a thread ibrar! avai ab e on host machine. %threads Pthreads refers to the POSI4 standard defining an API for thread creation and s!nchronization. &his is specification for thread behavior$ not an imp ementation. %umerous s!stems imp ement the Pthreads specification inc uding So aris$ Linux$ 1ac OS 4$ and &ru>: "%I4. &he two threads. the initia thread in main<= and the summation thread performing the summation operation in the runner<= function. After creating the summation thread$ the parent thread wi wait for it to comp ete b! ca ing the pthread 3oin function. 1in89 hreads &he techni(ue for creating threads using the 2in6, thread ibrar! is simi ar to the Pthreads techni(ue in severa wa!s. &hreads are created in the 2in6, API using the Create&hread<= function and 3ust as in Pthreads a set of attributes for the thread is passed to this function. &hese attributes inc ude securit! information$ the size of the stack$ and a f ag that can be set to indicate if the thread is to start in a suspended state. 2e use the defau t va ues for these attributes not initia ! set the thread to suspended state and instead make it e igib e to be run b! the CP" schedu er. :ava hreads &hreads are the fundamenta mode of program execution in a Aava program$ and the Aava anguage and its API provide a rich set of features for the creation and management of threads. A Aava programs comprise at east a sing e thread of contro . &here are two

*ept. of CS#$ AI&$ 'anga ore

,-++)+,

Advances in OS Lab Programs techni(ues for creating threads in Aava program. One approach is to create a new c ass that is derived from the thread c ass and to override its run<= method. An a ternative and more common ! used techni(ue is to define a c ass that imp ements the 9un ab e interface. hreading Issues Some of the issues to consider a mu tithreaded program uses s!stems are &he fork<= s!stem ca #xec<= s!stem ca ;or7<= and exec<=system call, fork is used to create a separate$ dup icate process. If one thread in a program ca s does the new process dup icate a threads$ or is the process. Some "%I4 s!stems have chosen to have two version of fork<=$ one that dup icates a threads and another that dup icates on ! the thread that invoked the fork<= s!stem ca . &he program specified in the parameters to ecec<= wi rep ace the process. *up icating on ! the ca ing threads is appropriate$ the separate process does not ca exec<= after forking the separate process shou d dup icate a threads. 'ource $ode, import 3ava.uti .9andom8 import 3ava.io.D8 pub ic c ass Create&hreads E pub ic static void main<String argsFG= E tr! E int noOf&hreads8 'uffered9eader br H new 'uffered9eader<new InputStream9eader< S!stem.in==8 S!stem.out.print n<I#nter the 9e(uired %umber Of &hreadsJnI=8 noOf&hreadsH Integer.parseInt<br.readLine<==8 for <int index H -8 index K noOf&hreads8 indexLL= E Prime%um&hread P H new Prime%um&hread<=8 M

*ept. of CS#$ AI&$ 'anga ore

+-

,-++)+,

Advances in OS Lab Programs M catch <#xception e= M M//end of main method M//end of c ass Create&hreads c ass Prime%um&hread extends &hread E Prime%um&hread<= E start<=8 M pub ic void run<= E 9andom randomOb3ectHnew 9andom<=8 int upperLimitHrandomOb3ect.nextInt<,-=8 S!stem.out.print n<I&he upper imit of ILPrime%um&hread.current&hread<=LI is ILupperLimitLIJnJnI=8 for<int iH,8iKHupperLimit8iLL= E if<isPrime%um<i== S!stem.out.print n<I&hread%ame. ILPrime%um&hread.current&hread<=.get%ame<=LI And ILIprime%umber within.ILupperLimitLI)))N I Li=8 tr! E s eep<+---=8 M catch<Interrupted#xception e=EM M M//end of run method pub ic boo ean isPrime%um<int num= E boo ean f agH true8

*ept. of CS#$ AI&$ 'anga ore

++

,-++)+,

Advances in OS Lab Programs int imit H <int= 1ath.s(rt<num=8 for <int index H ,8 index KH imit8 indexLL= E if <num O index HH -= E f ag H fa se8 break8 M M return f ag8 M//end of is Prime%um method M// end of Prime%um &hread c ass "utput #nter the 9e(uired %umber Of &hreads ; &he upper imit of &hreadF&hread)-$;$mainG is + &he upper imit of &hreadF&hread),$;$mainG is C &he upper imit of &hreadF&hread):$;$mainG is +C &hread%ame. &hread): And prime%umber within.+C)))N , &he upper imit of &hreadF&hread)+$;$mainG is &he upper imit of &hreadF&hread)6$;$mainG is +; &hread%ame. &hread), And prime%umber within.C)))N , &hread%ame. &hread)6 And prime%umber within.+;)))N , &hread%ame. &hread): And prime%umber within.+C)))N 6 &hread%ame. &hread)6 And prime%umber within.+;)))N 6 &hread%ame. &hread), And prime%umber within.C)))N 6 &hread%ame. &hread)6 And prime%umber within.+;)))N ; &hread%ame. &hread), And prime%umber within.C)))N ; &hread%ame. &hread): And prime%umber within.+C)))N ; &hread%ame. &hread), And prime%umber within.C)))N ? &hread%ame. &hread): And prime%umber within.+C)))N ? &hread%ame. &hread)6 And prime%umber within.+;)))N ?

*ept. of CS#$ AI&$ 'anga ore

+,

,-++)+,

Advances in OS Lab Programs &hread%ame. &hread)6 And prime%umber within.+;)))N ++ &hread%ame. &hread): And prime%umber within.+C)))N ++ &hread%ame. &hread)6 And prime%umber within.+;)))N +6 &hread%ame. &hread): And prime%umber within.+C)))N +6 &hread%ame. &hread): And prime%umber within.+C)))N +? &hread%ame. &hread): And prime%umber within.+C)))N +C #nter the 9e(uired %umber Of &hreads + &he upper imit of &hreadF&hread)-$;$mainG is +@ &hread%ame. &hread)- And prime%umber within.+@)))N , &hread%ame. &hread)- And prime%umber within.+@)))N 6 &hread%ame. &hread)- And prime%umber within.+@)))N ; &hread%ame. &hread)- And prime%umber within.+@)))N ? &hread%ame. &hread)- And prime%umber within.+@)))N ++ &hread%ame. &hread)- And prime%umber within.+@)))N +6 &hread%ame. &hread)- And prime%umber within.+@)))N +?

IN !"D#$ I"N %rocess is a program in execution. Process is a passive entit! with a program counter specif!ing the next instruction to execute and a set of associated resources. #ach process is represented in the operating s!stem b! a process control bloc7 <%$*= a so ca ed a tas7 control bloc7. It contains information such as process state$ program counter$ cpu registers. 'ystem calls,

*ept. of CS#$ AI&$ 'anga ore

+6

,-++)+,

Advances in OS Lab Programs It provide the interface between a process and the operating s!stem. It is a routine bui t in the kerne to perform function that re(uires communication with the s!stem0s hardware. A activities re ated to fi e hand ing$ process and memor! management and maintenance of user and s!stem information are hand ed b! the kerne using these s!stem ca s. 5or examp e. when we execute a C program$ the CP" runs in user mode ti a s!stem ca is invoked. In this mode$ the process has access to a imited section of the computer0s memor! and can execute a restricted set of machine instructions. 7owever$ when the process invokes a s!stem ca $ the CP" switches from user mode to a more privi eged mode i.e.$ the kerne mode. In this mode$ it0s kerne that runs on beha f of the user. After the s!stem ca has returned$ the CP" switches back to user mode for further execution. &he "nix and Linux Os uti izes same s!stem ca s. Portab e Operating s!stem Interface for Computer #nvironments < POSI4.+=specifies the C API that contains the bui t)in S!stem ca s.

<the users= She s and commands Compi ers and interpreters S!stem ibraries S!stem) ca interface to the kerne

*ept. of CS#$ AI&$ 'anga ore

+:

,-++)+,

Advances in OS Lab Programs

Signa s termina hand ing

fi e s!stem hand ing

CP" schedu ing page rep acement

Perne interface to the hardware &ermina contro ers $ termina s *isks tapes and *evice contro ers Ph!sica memor! 1emor! contro ers

Fig. LINUX system structure +ernel A Perne timer is a data structure that instructs the kerne to execute a user) defined function with a user)defined argument at a user)defined time. In computing$ the 7ernel is the main component of most computer operating s!stems8 it is a bridge between app ications and the actua data processing done at the hardware eve . &he kerne Qs responsibi ities inc ude managing the s!stemQs resources <the communication between hardware and software components=. "sua ! as a basic component of an operating s!stem$ a kerne can provide the owest) eve abstraction a!er for the resources <especia ! processors and I/O devices= that app ication software must contro to perform its function. It t!pica ! makes these faci ities avai ab e to app ication processes through inter)process communication mechanisms and s!stem ca s. Operating s!stem tasks are done different ! b! different kerne s$ depending on their design and imp ementation. 2hi e mono ithic kerne s execute a the operating s!stem code in the same address space to increase the performance of the s!stem$ microkerne s run most of the operating s!stem services in user space as servers$ aiming to improve maintainabi it! and modu arit! of the operating s!stem.

*ept. of CS#$ AI&$ 'anga ore

+;

,-++)+,

Advances in OS Lab Programs %rocessor time &he amount of time a process takes to run$ given that it has exc usive and uninterrupted use of the CP". %ote that in a modern computer$ this wou d be ver! unusua $ and so the processor time ca cu ation for most processes invo ves adding up a the sma amounts of time the CP" actua ! spends on the process. Some s!stems break processor time down into user time and s!stem time. !eal time 9ea )time operating s!stems are s!stems that respond to input immediate !. &he! are used for such tasks as navigation$ in which the computer must react to a stead! f ow of new information without interruption. 9ea time is the amount of time spent between process creation upto the end of process execution is considered. #ser space time "ser space is that portion of s!stem memor! in which user processes run. &he amount of time spent b! a process in user mode from the time of creation to its process termination is ca ed user space time. A process is an executing <i.e.$ running= instance of a program. "ser processes are instances of a programs other than the kerne <i.e.$ uti it! and app ication programs=. 2hen a program is to be run$ it is copied from storage into user space so that it can be accessed at high speed b! the CP" <centra processing unit=. +ernel space time &he kerne is a program that constitutes the centra core of a computer operating s!stem. It is not a process$ but rather a contro er of processes$ and it has comp ete contro over ever!thing that occurs on the s!stem. &his inc udes managing individua user processes within user space and preventing them from interfering with each other. +ernel space It is that portion of memor! in which the kerne executes and provides its services. Perne space time is the amount of time taken b! kerne to execute s!stem ca s and other interrupt services in kerne mode. &he division of s!stem memor! in Linux) ike operating

*ept. of CS#$ AI&$ 'anga ore

+>

,-++)+,

Advances in OS Lab Programs s!stems into user space and kerne space p a!s an important ro e in maintaining s!stem stabi it! and securit!.

D&'I/N ( gorithm to create the chi d processes$ a so find the rea time$ processor time$ user space time R kerne space time for each process after creating. A so disp a! the rea time$ user space time R kerne space time of the parent process (lgorithm, Create Process< = ..purpose, &o create chi d process for i- to , do if <fork< = HH -= // fork s!stem ca is used to create chi d process

*ept. of CS#$ AI&$ 'anga ore

+?

,-++)+,

Advances in OS Lab Programs Chi dSprocess<i=8 endif endfor for i- to , do 2ait< = // process enters this state when other process is under execution endfor (lgorithm, Chi dSprocess<processSno= ..%urpose, &o generate tota prime no and find rea time$ processor time$ user space time$ kerne space time of each chi d process // Input, processSno // "utput, // // // // // processor time at chi d is created generate random no. R tota prime no. of each chi d process rea time of chi d process user space time of chi d process kerne space time of chi d process // generate random no. using rand< = function

time Chi d process //find processor time R store in variab e 9and rand< = O const va ue &ota SprimeSno for n - to nK 9and do primeH+ // Initia ize prime to + for i, to iK n do if < n O i H -= primeHend if end for // if prime is true va ue ie + it increments variab e tota SprimeSno. if <prime= increment tota SprimeS no. // if n is not prime

*ept. of CS#$ AI&$ 'anga ore

+@

,-++)+,

Advances in OS Lab Programs end if end for // after generating tota prime no. the respective time of each chi d process and tota prime is shown print tota prime number print rea time of chi d process print user space time of chi d process print kerne space time of chi d process //2hen the two chi d process terminates$ the fo owing respective time is shown print rea time of parent process print user space time of parent process print kerne space time of parent process // #nd of a gorithm

I-%)&-&N ( I"N Let us consider the Linux operating s!stem for imp ementation. 7ere each process is identified b! its process identifier$ which is a uni(ue integer. A new process is created b! the fork s!stem ca <chi d process=. &he chi d process consists of a cop! of the address space of the origina process. &his mechanism a ows the parent process to communicate easi ! with its chi d process. 'oth processes <the parent and the chi d= continue execution at the instruction after the fork s!stem ca $ with one difference. &he va ue of pid for the chi d process is zero but for the parent is an integer va ue greater than zero.

*ept. of CS#$ AI&$ 'anga ore

+C

,-++)+,

Advances in OS Lab Programs

In this program$ times < = function which is bui t in s!s/times header fi e. It stores the current process time in struct tms datat!pe. &he struct tms is defined in Ks!s/times.hN as fo ows. Struct tms E c ockSt tmsSutime8 $ c ockSt tmsSstime8 c ockSt tmsScstime8 M Tinc ude Kstdio.hN Tinc ude Kstd ib.hN Tinc ude Kunistd.hN Tinc ude Ks!s/times.hN chi dSprocess<int processSno= E int i$ n$ prime$ &otPrime%oH-8 struct tms chprSt+$ chprSt,8 ong rchprt+$ rchprt,8 int 9and8 rchprt+ H times<RchprSt+=8 //start time of chi d process printf<IJn Processor time for chi d process <Od= H OdI$ <processSno L+=$ rchprt+=8 printf<IJn Created chi d process Od I$ processSnoL+=8 srand<processSno=8 9and H random<= O +----8 printf<I Jn 9andom number H OdJtI$ 9and =8 // tota prime no generation for<nH-8 nK9and8 nLL= E prime H +8 // initia ize // s!stem time // s!stem time of chi dren c ockSt tmsScutime8 // user time of chi dren // user time

*ept. of CS#$ AI&$ 'anga ore

,-

,-++)+,

Advances in OS Lab Programs for<iH,8 iKn8 iLL= E if<n O i HH -= E prime H -8 break8 M M if<prime= E &otPrime%oLL8 M M printf<IJn&ota Prime %osHOdJnI$ &otPrime%o=8 rchprt, H times<RchprSt,=8 // end time of chi d process printf<U))))))))))))) &he rea time$ user space and kerne space for chid process are. )))))))))))))))U= printf<IJn 9ea time for chi d process <Od= H OdI$ <processSno L+=$ <rchprt,) rchprt+==8 printf<IJn "ser space time for chi d process<Od= H OdI$ <processSno L+=$ <chprSt,.tmsScutime )chprSt+.tmsScutime==8 printf<IJn kerne space time for chi d process<Od= H OdJnJnI$ <processSno L+=$ <chprSt,.tmsScstime ) chprSt+.tmsScstime==8 exit<-=8 M void CreateProcess<=

*ept. of CS#$ AI&$ 'anga ore

,+

,-++)+,

Advances in OS Lab Programs E int i8 for <iH-8 iK,8iLL= E if<fork< = HH -= chi dSprocess<i=8 M for <iH-8 iK,8iLL= E wait< =8 M M int main <= E ong pSmt+$ pSmt,8 struct tms pSmst+$ pSmst, pSmt+ H times<RpSmst+=8 //start time of a parent process CreateProcess<=8 pSmt, H times<RpSmst,=8 // end time of a parent process printf<U))))))))))))) &he rea time$ user space and kerne space for parent process are. )))))))/nV=8 printf<IJn 9ea time for parent process H OdI$ pSmt,)pSmt+=8 printf<IJn "ser space time for parent process H OdI$<pSmst,.tmsSutime ) pSmst+.tmsSuti me==8 printf<IJn Perne space time for parent process H OdJnJnI$<pSmst,.tmsSstime ) pSmst+.tmsSsti me==8 M "utput, Processor time for chi d process <+= H +@@:?@C?

*ept. of CS#$ AI&$ 'anga ore

,,

,-++)+,

Advances in OS Lab Programs Created chi d process + Processor time for chi d process <,= H +@@:?@C? Created chi d process , 9andom number H ,@C6@6 &ota Prime %oH,;+@))))))))))))) &he rea time$ user space and kerne space for chid process are. ))))))))))))))) 9ea time for chi d process <,= H +:-, "ser space time for chi d process<,= H kerne space time for chi d process<,= H 9andom number H ,@C6@6 &ota Prime %oH,;+@))))))))))))) &he rea time$ user space and kerne space for chid process are. ))))))))))))))) 9ea time for chi d process <+= H +:,, "ser space time for chi d process<+= H kerne space time for chi d process<+= H ))))))))))))) &he rea time$ user space and kerne space for parent process are. ))))))) 9ea time for parent process H +:,: "ser space time for parent process H Perne space time for parent process H -

Design, develop and implement a process with a producer thread and a consumer thread which ma7e use of bounded buffer <si6e can be prefixed at a suitable value= for communication. #se any suitable synchroni6ation construct.
IN !"D#$ I"N Interprocess Communication is a mechanism$ for processes to communicate and to s!nchronize their actions. It has a set of methods for the exchange of data among mu tip e threads in one or more processes.

*ept. of CS#$ AI&$ 'anga ore

,6

,-++)+,

Advances in OS Lab Programs

&he U'ounded)'uffer <Producer)Consumer= prob emV is to create producer thread and consumer thread a ows process to communicate and to s!nchronize their actions with the use of a bounded buffer. &he bounded)buffer prob em is a paradigm for cooperating processes$ where the producer process produces information that is consumed b! a consumer process. &he producer and the consumer$ who share a common$ fixed)size buffer. &he producerQs 3ob is to generate a piece of data$ put it into the buffer and start again. At the same time the consumer is consuming the data <i.e.$ removing it from the buffer= one piece at a time. &he prob em is to make sure that the producer wonQt tr! to add data into the buffer if itQs fu and that the consumer wonQt tr! to remove data from an empt! buffer. It consists of four c asses. W$ the (ueue that !ou0re tr!ing to s!nchronize. Producer$ the threaded ob3ect that is producing (ueue entries. Consumer$ the threaded ob3ect that is consuming (ueue entries$ and PC$ the tin! c ass that creates the sing e W$ Producer$ and Consumer. &he ke! idea behind s!nchronization techni(ue is to maintain data consistenc!$ order ! execution of cooperating processes and preventing race condition.

'tatement of the %roblem &he pro3ect entit ed UInterprocess CommunicationV has been designed using bounded) buffer prob em to provide better paradigm for cooperating processes compare to other prob ems. Producer)consumer prob em <a so known as the bounded)buffer prob em= is a c assica examp e of a mu ti)process s!nchronization prob em. &he prob em describes two processes$ the producer and the consumer$ who share a common$ fixed)size buffer. &he producerQs 3ob is to generate a piece of data$ put it into the buffer and start again. At the

*ept. of CS#$ AI&$ 'anga ore

,:

,-++)+,

Advances in OS Lab Programs same time the consumer is consuming the data <i.e.$ removing it from the buffer= one piece at a time. &he prob em is to make sure that the producer wonQt tr! to add data into the buffer if itQs fu and that the consumer wonQt tr! to remove data from an empt! buffer. "b>ective of study O Provides a genera 3ava mode for Interprocess communication. O I ustrate the use of the mode . O 9eview studies of process and threads. 'cope of the 'tudy In our program we wi demonstrate how two or more process access the shared information without causing race condition. !eview of )iterature O Process O &hreads O S!nchronization O Aava Scripts %rocess, ( program in execution or instance of a executing program. Process execution must progress in se(uentia fashion. A process inc udes. O program counter O stack O data section hreads, &hread is a ight weight process or thread is the sma est unit of dispatchab e code. &his means that a sing e program can perform two or more tasks simu taneous !. 'ynchroni6ation, 1essage passing ma! be either b ocking or non)b ocking.
O ' ocking is considered s!nchronous. O %on)b ocking is considered as!nchronous.

:ava 'cripts, AavaScript is an ob3ect based scripting anguage that offers cross p atform operation across the span of the 222. AavaScript provides a means of embedding

*ept. of CS#$ AI&$ 'anga ore

,;

,-++)+,

Advances in OS Lab Programs interactive paths and inte igence within 7&1L documents. &he ob3ect)based nature of AavaScript offers programmers significant power and f exibi it! through the abi it! to create functions and new ob3ects. Performing certain processing functions at the c ient side X such as form va idation and data retrieva from oca data arra!s)reduces the burden imposed on the server side and can provide a sense of greater responsiveness to a viewer an 7&1L document enhanced with AavaScript.

D&'I/N &his pro3ect can be divided main ! into four parts +. Producer. ,. Consumer. 6. 'ounded)'uffer. :. Integration of a three.

*ept. of CS#$ AI&$ 'anga ore

,>

,-++)+,

Advances in OS Lab Programs %roducer, Producer corresponds to produce the item and stores in the buffer. After storing the item in the buffer$ it has to increment the counter a so it has to notice the consumer to consume the item. $onsumer consumes the item, Consumer corresponds to consume the item avai ab e in the buffer. After consuming the item in the buffer$ it has to decrement the counter a so it has to notice the consumer to consume the item. *ounded3*uffer, It works as the interface between the Producer and the Consumer. It a ows the producer to store the item in the buffer <shared space=$ a so a ows the consumer to consume the item from the buffer <shared space=. Integration of all three, 5ina ! we integrate these three parts of the prob em using the s!nchronization techni(ue of 3ava. Interprocess $ommunication <I%$= O 1echanism for processes to communicate and to s!nchronize their actions. O 1essage s!stem X processes communicate with each other without resorting to shared variab es. O IPC faci it! provides two operations.

send<message= X message size fixed or variab e receive<message=

O If A and ' wish to communicate$ the! need to.

#stab ish a communication ink between them. #xchange messages via send/receive.

O Imp ementation of communication ink ph!sica <e.g.$ shared memor!$ hardware bus= ogica <e.g.$ ogica properties=

%roducer3$onsumer %roblem Producer)consumer prob em <a so known as the bounded)buffer prob em= is a c assica examp e of a mu ti)process s!nchronization prob em. &he prob em describes two processes$ the producer and the consumer$ who share a common$ fixed)size buffer. &he

*ept. of CS#$ AI&$ 'anga ore

,?

,-++)+,

Advances in OS Lab Programs producerQs 3ob is to generate a piece of data$ put it into the buffer and start again. At the same time the consumer is consuming the data <i.e.$ removing it from the buffer= one piece at a time. &he prob em is to make sure that the producer wonQt tr! to add data into the buffer if itQs fu and that the consumer wonQt tr! to remove data from an empt! buffer. &he so ution for the producer is to either go to s eep or discard data if the buffer is fu . &he next time the consumer removes an item from the buffer$ it notifies the producer who starts to fi the buffer again. In the same wa!$ the consumer can go to s eep if it finds the buffer to be empt!. &he next time the producer puts data into the buffer$ it wakes up the s eeping consumer. &he so ution can be reached b! means of inter)process communication$ t!pica ! using semaphores. An inade(uate so ution cou d resu t in a dead ock where both processes are waiting to be awakened. &he prob em can a so be genera ized to have mu tip e producers and consumers. Producer)Consumer prob em is a paradigm for cooperating processes8 producer process produces information that consumer process consumes the information.
O "nbounded)buffer p aces no practica imit on the size of the buffer. O 'ounded)buffer assumes that there is a fixed buffer size.

(dvantages of $o3operating process O Information sharing O Computation speed)up O 1odu arit! O Convenience

hreads &hread is a ight weight process or the thread is the sma est unit of dispatchab e code. &his means that a sing e program can perform two or more tasks simu taneous !. ypes of hreads a. #ser level hreads, &hread management done b! user) eve threads ibrar! #xamp es. POSI4 Pthreads, 1ach C-threads, So aris threads

*ept. of CS#$ AI&$ 'anga ore

,@

,-++)+,

Advances in OS Lab Programs b. +ernel level hreads, Supported b! the Perne #xamp es. 2indows C;/C@/%&/,---$ So aris$ &ru>: "%I4$ 'eOS$ Linux :ava hreads Aava threads are managed b! the AB1. Aava threads can be created b!. O Imp ementing the 9unnab e interface O #xtending &hread c ass 'ynchroni6ation 1essage passing ma! be either b ocking or non)b ocking.
O ' ocking is considered s!nchronous. O %on)b ocking is considered as!nchronous.

Send and receive primitives ma! be either b ocking or non)b ocking. 1hy we need %rocess 'ynchroni6ation? O Concurrent access to shared data ma! resu t in data inconsistenc!. O 1aintaining data consistenc! re(uires mechanisms to ensure the order ! execution of cooperating processes.
O !ace condition. &he situation where severa processes access X and manipu ate

shared data concurrent !. &he fina va ue of the shared data depends upon which process finishes ast.
O &o prevent race conditions$ concurrent processes must be synchroni6ed.

S!nchronized <object= E // statements to be s!nchronized M 7ere$ object is a reference to the ob3ect being s!nchronized. A s!nchronized b ock ensures that a ca to a method that is a member of object occurs on ! after the current thread has successfu ! entered object0s monitor.

*ept. of CS#$ AI&$ 'anga ore

,C

,-++)+,

Advances in OS Lab Programs 7ere is an a ternative version of the preceding examp e$ using a s!nchronized b ock within the run< = method. // &his program uses a s!nchronized b ock. c ass Ca me E void ca <String msg= E S!stem.out.print<IFI L msg=8 tr! E &hread.s eep<+---=8 M catch <Interrupted#xception e= E S!stem.out.print n<IInterruptedI=8 M S!stem.out.print n<IGI=8 M M c ass Ca er imp ements 9unnab e E String msg8 Ca me target8 &hread t8 pub ic Ca er<Ca me targ$ String s= E target H targ8 msg H s8 t H new &hread<this=8 t.start<=8 M // s!nchronize ca s to ca <= pub ic void run<= E s!nchronized<target= E // s!nchronized b ock target.ca <msg=8 M M

*ept. of CS#$ AI&$ 'anga ore

6-

,-++)+,

Advances in OS Lab Programs M c ass S!nch+ E pub ic static void main<String argsFG= E Ca me target H new Ca me<=8 Ca er ob+ H new Ca er<target$ I7e oI=8 Ca er ob, H new Ca er<target$ IS!nchronizedI=8 Ca er ob6 H new Ca er<target$ I2or dI=8 // wait for threads to end tr! E ob+.t.3oin<=8 ob,.t.3oin<=8 ob6.t.3oin<=8 M catch<Interrupted#xception e= E S!stem.out.print n<IInterruptedI=8 M M M 7ere$ the call< = method is not modified b! synchroni6ed. Instead$ the synchroni6ed statement is used inside $aller0s run< = method. &his causes the same correct output as the preceding examp e$ because each thread waits for the prior one to finish before proceeding.

I-%)&-&N ( I"N (lgorithm %roducer process, //item nextProduced8 whi e <bufferSsize H HmaxSsize= E $onsumer process, //item to be Consumed8 whi e <bufferSsize H H -= E

*ept. of CS#$ AI&$ 'anga ore

6+

,-++)+,

Advances in OS Lab Programs 8 /D do nothing D/ wait< =8 M Add item into buffer8 notif!< =8 M 9emove item from buffer8 notif!< =8 8 /D do nothing D/ wait< =8

;low Diagram %!"D#$&!


Producer is created Notifies to producer

$"N'#-&!
Consumer is created

Producer produces Item Producer stores item in buffer Producer aits

Asks consumer to wait

Consumer

aits

Notifies to consumer

Consumer receives notification Consumer c!ecks buffer Consumer consumes Item Consumer Leaves

Asks producer to wait

Producer receives notification Producer aits for ne"t consumer

Notifies to producer

5igure 6.+. 5 ow diagram of Producer Consumer Prob em

he hread $lass and the !unnable Interface Aava0s mu tithreading s!stem is bui t upon the companion interface$ !unnable. hread c ass$ its methods$ and its hread encapsu ates a thread of execution. Since !ou

can0t direct ! refer to the etherea state of a running thread$ !ou wi dea with it through its prox!$ the hread instance that spawned it. &o create a new thread$ !our program wi either extend hread or imp ement the !unnable interface.

*ept. of CS#$ AI&$ 'anga ore

6,

,-++)+,

Advances in OS Lab Programs &he hread c ass defines severa methods that he p manage threads. &he ones that wi -eaning Obtain a thread0s name. Obtain a thread0s priorit!. *etermine if a thread is sti running. 2ait for a thread to terminate. #ntr! point for the thread. Suspend a thread for a period of time. Start a thread b! ca ing its run method. the examp es in this book have used a sing e thread of execution. &he hread and !unnable to create and

be used in this chapter are shown here. -ethod get%ame getPriorit! isA ive 3oin run s eep start &hus far$ a

remainder of this chapter exp ains how to use thread. he -ain hread

manage threads$ beginning with the one thread that a Aava programs have the main

2hen a Aava program starts up$ one thread begins running immediate !. &his is usua ! ca ed the main thread of !our program$ because it is the one that is executed when !our program begins. &he main thread is important for two reasons. O It is the thread from which other Uchi dV threads wi be spawned. O Often it must be the ast thread to finish execution because it performs various shutdown actions. A though the main thread is created automatica ! when !our program is started$ it can be contro ed through a hread ob3ect. &o do so$ !ou must obtain a reference to it b! ca ing the method current hread< =$ which is a public static member of hread. $reating the hreads Aava threads can be created b!. O Implementing the !unnable interface &he easiest wa! to create a thread is to create a c ass that imp ements the !unnable interface. !unnable abstracts a unit of executab e code. You can construct a thread on

*ept. of CS#$ AI&$ 'anga ore

66

,-++)+,

Advances in OS Lab Programs an! ob3ect that imp ements !unnable. &o imp ement !unnable$ a c ass need on ! imp ement a sing e method ca ed run < =$ which is dec ared ike this. pub ic void run< = Inside run < =$ !ou wi define the code that constitutes the new thread. It is important to understand that run< = can ca other methods$ use other c asses$ and dec are variab es$ 3ust ike the main thread can. &he on ! difference is that run < = estab ishes the entr! point for another$ concurrent thread of execution within !our program. &his thread wi end when run < = returns. After !ou create a c ass that imp ements !unnable$ !ou wi instantiate an ob3ect of t!pe hread from within that c ass. hread defines severa constructors. &he one that we wi use is shown here. &hread<9unnab e threadOb$ String threadName= In this constructor$ threadOb is an instance of a c ass that imp ements the !unnable interface. &his defines where execution of the thread wi begin. &he name of the new thread is specified b! threadName. After the new thread is created$ it wi not start running unti !ou ca its start < = method$ which is dec ared within hread. In essence$ start < = executes a ca to run < =. &he start < = method is shown here. void start < = Example: // Create a second thread. c ass %ew&hread imp ements 9unnab e E &hread t8 %ew&hread< = E // Create a new$ second thread t H new &hread<this$ I*emo &hreadI=8 S!stem.out.print n<IChi d thread. I L t=8 t.start<=8 // Start the thread M // &his is the entr! point for the second thread. pub ic void run<= E tr! E for<int i H ;8 i N -8 i))= E S!stem.out.print n<IChi d &hread. I L i=8

*ept. of CS#$ AI&$ 'anga ore

6:

,-++)+,

Advances in OS Lab Programs &hread.s eep<;--=8 M M catch <Interrupted#xception e= E S!stem.out.print n<IChi d interrupted.I=8 M S!stem.out.print n<I#xiting chi d thread.I=8 M M c ass &hread*emo E pub ic static void main<String argsFG= E new %ew&hread< =8 // create a new thread tr! E for<int i H ;8 i N -8 i))= E S!stem.out.print n<I1ain &hread. I L i=8 &hread.s eep<+---=8 M M catch <Interrupted#xception e= E S!stem.out.print n<I1ain thread interrupted.I=8 M S!stem.out.print n<I1ain thread exiting.I=8 M M O &xtending hread class &he second wa! to create a thread is to create a new c ass that extends hread$ and then to create an instance of that c ass. &he extending c ass must override the run< = method$ which is the entr! point for the new thread. It must a so ca start< = to begin execution of the new thread. 7ere is the preceding program rewritten to extend hread. Example: 5& :(@( )(N/#(/& // Create a second thread b! extending &hread c ass %ew&hread extends &hread E %ew&hread< = E // Create a new$ second thread super<I*emo &hreadI=8 S!stem.out.print n<IChi d thread. I L this=8

*ept. of CS#$ AI&$ 'anga ore

6;

,-++)+,

Advances in OS Lab Programs start<=8 // Start the thread M // &his is the entr! point for the second thread. pub ic void run<= E tr! E for<int i H ;8 i N -8 i))= E S!stem.out.print n<IChi d &hread. I L i=8 &hread.s eep<;--=8 M M catch <Interrupted#xception e= E S!stem.out.print n<IChi d interrupted.I=8 M S!stem.out.print n<I#xiting chi d thread.I=8 M M c ass #xtend&hread E pub ic static void main<String argsF G= E new %ew&hread< =8 tr! E for<int i H ;8 i N -8 i))= E S!stem.out.print n<I1ain &hread. I L i=8 &hread.s eep<+---=8 M M catch <Interrupted#xception e= E S!stem.out.print n<I1ain thread interrupted.I=8 M S!stem.out.print n<I1ain thread exiting.I=8 M M &his program generates the same output as the preceding version. As !ou can see$ the chi d thread is created b! instantiating an ob3ect of New hread$ which is derived from // create a new thread

*ept. of CS#$ AI&$ 'anga ore

6>

,-++)+,

Advances in OS Lab Programs hread. %otice the ca to super< = inside New hread. &his invokes the fo owing form of the hread constructor. pub ic &hread<String threadName= 7ere$ threadName specifies the name of the thread. Interthread $ommunication 1u tithreading rep aces event oop programming b! dividing !our tasks into discrete and ogica units. &hreads a so provide a secondar! benefit the! do awa! with po ing. Po ing is usua ! imp emented b! a oop that is used to check some condition repeated !. Once the condition is true$ appropriate action is taken. &his wastes CP" time. 5or examp e$ consider the c assic (ueuing prob em$ where one thread is producing some data and another is consuming it. In a po ing s!stem$ the consumer wou d waste man! CP" c!c es whi e it waited for the producer to produce. Once the producer was finished$ it wou d start po ing$ wasting more CP" c!c es waiting for the consumer to finish$ and so on. C ear !$ this situation is undesirab e. &o avoid po ing$ Aava inc udes an e egant interthread communication mechanism via the wait< =$ notify< =$ and notify(ll< = methods. &hese methods are imp emented as final methods in "b>ect$ so a c asses have them. A three methods can be ca ed on ! from within a synchroni6ed context. A though conceptua ! advanced from a computer science perspective$ the ru es for using these methods are actua ! (uite simp e.
O wait< = te s the ca ing thread to give up the monitor and go to s eep unti some

other thread enters the same monitor and ca s notify< =.


O notify< = wakes up the first thread that ca ed wait< = on the same ob3ect. O notify(ll< = wakes up a the threads that ca ed wait< = on the same ob3ect.

&he highest priorit! thread wi run first. &hese methods are dec ared within "b>ect$ as shown here. O fina void wait< = throws Interrupted#xception O fina void notif!< = O fina void notif!A < = Additiona forms of wait< = exist that a ow !ou to specif! a period of time to wait. &he fo owing samp e program incorrect ! imp ements a simp e form of the producer) consumer prob em. It consists of four c asses. A$ the (ueue that !ou0re tr!ing to

*ept. of CS#$ AI&$ 'anga ore

6?

,-++)+,

Advances in OS Lab Programs s!nchronize8 %roducer$ the threaded ob3ect that is producing (ueue entries. $onsumer$ the threaded ob3ect that is consuming (ueue entries8 and %$$ the tin! c ass that creates the sing e A$ %roducer$ and $onsumer. Inside get< =$ wait< = is ca ed. &his causes its execution to suspend unti the %roducer notifies !ou that some data is read!. 2hen this happens$ execution inside get< = resumes. After the data has been obtained$ get< = ca s notify< =. &his te s %roducer that it is oka! to put more data in the (ueue. Inside put< =$ wait< = suspends execution unti the $onsumer has removed the item from the (ueue. 2hen execution resumes$ the next item of data is put in the (ueue$ and notify< = is ca ed. &his te s the $onsumer that it shou d now remove it. 'ource $ode, import 3ava.uti .Arra!List8 import 3ava.uti .List8 c ass ProducerSConsumer E pub ic static fina int '"55#9SSIZ# H :8 pub ic static fina int &O&ALSBAL"#S H +-8 pub ic static void main<String argsFG= E Shared'uffer m H new Shared'uffer<=8 Producer prod H new Producer<m=8 Consumer cons H new Consumer<m=8 prod.start<=8 cons.start<=8 M M c ass Shared'uffer E private ListKIntegerN buffer H new Arra!ListKIntegerN<ProducerSConsumer.'"55#9SSIZ#=8 pub ic s!nchronized int get<= E whi e <buffer.size<= HH -= E tr! E wait<=8 M

*ept. of CS#$ AI&$ 'anga ore

6@

,-++)+,

Advances in OS Lab Programs catch <Interrupted#xception e= EM M notif!<=8 return buffer.remove<-=8 M pub ic s!nchronized void put<int message= E whi e <buffer.size<= HH ProducerSConsumer.'"55#9SSIZ#= E tr! E wait<=8 M catch <Interrupted#xception e= EM M buffer.add<message=8 notif!<=8 M M c ass Producer extends &hread E private Shared'uffer shbuf8 pub ic Producer<Shared'uffer m= E shbuf H m8 M pub ic void run<= E int 38 for <int i H -8 i K ProducerSConsumer.&O&ALSBAL"#S8 iLL= E 3 H <int= <1ath.random<= D +---=8 shbuf.put<3=8 S!stem.out.print n<IProducer p aced. I L 3=8 tr! E s eep<<int= <1ath.random<= D +--==8 M catch <Interrupted#xception e= E M M M M c ass Consumer extends &hread E private Shared'uffer shbuf8 pub ic Consumer<Shared'uffer m= E shbuf H m8 M

*ept. of CS#$ AI&$ 'anga ore

6C

,-++)+,

Advances in OS Lab Programs pub ic void run<= E int message H -8 for <int i H -8 i K ProducerSConsumer.&O&ALSBAL"#S8 iLL= E message H shbuf.get<=8 S!stem.out.print n<IConsumer consumed. I L message=8 tr! E s eep<<int= <1ath.random<= D +--==8 M catch <Interrupted#xception e= EM M M M "utput,

*ept. of CS#$ AI&$ 'anga ore

:-

,-++)+,

Advances in OS Lab Programs

B.

C.
IN !"D#$ I"N Procedure Ca <9PC= defines a powerfu techno og! for creating distributed c ient/server programs. &he 9PC run)time stubs and ibraries manage most of the processes re ating to network protoco s and communication. &his enab es !ou to focus on the detai s of the app ication rather than the detai s of the network. #xamp es. 5i e service$ *atabase service$ and Authentication service. Need of !%$, &he c ient needs an eas! wa! to ca the procedures of the server to get some services.

9PC enab es c ients to communicate with servers b! ca ing procedures in a simi ar wa! to the conventiona use of procedure ca s in high) eve anguages. 9PC is mode ed on the oca procedure ca $ but the ca ed procedure is executed in a different process and usua ! a different computer.

Different !%$ 'ystems, Sun 9PC *C# 9PC *CO1 CO9'A Aava 91I 41L 9PC$ SOAP/.%#&$ AAA4$ 9#S&

'un !%$, An a ternative to sockets is 9PC. 9PC enab es an app ication to ca procedures that exist on another machine. 9PC makes a network connection to a remote machine using sockets. After the connection is made with the server$ one can invoke a function on the remote machine. &he programmer has the i usion of ca ing a oca procedure$ but actua ! the arguments are packaged and passed to the remote machine. 9PC is easier to use than sockets. here are some drawbac7s of using !%$, such as,

You can on ! pass simp e data t!pes R not ob3ects as arguments. &he programmer must earn a specia Interface *efinition Language <I*L=. :+ ,-++)+,

*ept. of CS#$ AI&$ 'anga ore

Advances in OS Lab Programs

$ommon "b>ect !equest *ro7er (rchitecture <$"!*(= CO9'A is a midd eware techno og! deve oped b! a consortium ca ed O1[ <Ob3ect 1anagement [roup=. It is used main ! for app ications in distributed architecture. 5undamenta to the Common Ob3ect 9e(uest 'roker Architecture is the Ob3ect 9e(uest 'roker <O9'=. An O9' is a software component used to estab ish communication between ob3ects. he advantages of $"!*( are,

It enab es access to software running on different p atforms. It is anguage neutra .

Distributed $omponent "b>ect -odel <D$"-= 1icrosoft<s= *CO1 is an extension of the CO1. CO1 is used to deve op distributed app ications on the same machine. *CO1 p aces CO1 app ications on the network. One of the imitations of using *CO1 is that it can communicate on ! between app ications deve oped in windows environment. !emote method Invocation <!-I= 91I is used to deve op distributed app ications. 91I has been specifica ! designed to operate in Aava environment. Ca ing a remote method is a most the same as ca ing a oca method. 91I uses a registr! service for registering and ocating ob3ects. A marsha ing of parameters and return va ues is taken care of b! the s!stem. An advantage of using 91I is that there is no need to earn another I*L anguage. 2-) !%$, \ \ \ \ \ \ #ar ! +CC@ *ata marsha ed into 41L messages X A re(uest and responses are human)readab e 41L #xp icit t!ping Litt e/no industr! support &ransport over 7&&P protoco X X So ves firewa issues Lots of support ibraries %o true I*L compi er support <!et=

*ept. of CS#$ AI&$ 'anga ore

:,

,-++)+,

Advances in OS Lab Programs

!-I (rchitecture, 91I s!stem a ows an ob3ect running in one AB1 to invoke methods on an ob3ect in another AB1. 91I can communicate on ! between programs written in Aava. 91I app ications often consist of two app ications. A sever and a c ient &he app ication is divided into ob3ects. A server creates remote ob3ects and registers these ob3ects with a simp e bootstrap name server ca ed a registry rmiregistry!. &he c ient gets a hand e b! ooking up the remote ob3ect b! its name in the server<s= registr! and invokes methods on it. !emote ob>ect A remote object is one whose methods can be invoked from another AB1 practica ! on a different machine. In situations where !ou do not have a network$ or a c ient$ or a server avai ab e to test programs$ !ou can invoke methods on a remote ob3ect from another AB1 on the same machine. A remote ob3ect must imp ement at east one interface that extends the 3ava.rmi.9emote interface. !emote Interface A remote inter"ace is an interface, which dec ares a set of methods that ma! be invoked remote ! <from a different AB1=. A interactions with the remote ob3ect wi be performed through this interface. A remote interface must direct ! or indirect ! extend the 3ava.rmi.9emote interface. #ach method dec aration in a remote interface must inc ude 3ava.rmi.9emote#xception or one of its superc asses in its throws c ause. 'tubs and '7eletons 2hen a c ient obtains a reference to a remote ob3ect$ the remote ob3ect is not sent over the network to the c ient. Actua !$ the c ient gets a prox! ob3ect or stub. A stub acts as a c ient<s= oca representative for the remote ob3ect. &he c ient invokes a method on the

*ept. of CS#$ AI&$ 'anga ore

:6

,-++)+,

Advances in OS Lab Programs oca stub. &he stub is responsib e for ca ing the method on the remote ob3ect. #ach c ient gets a cop! of stub ob3ect that represents the remote ob3ect. A remote ob3ect is not rep icated for ever! c ient. A stub imp ements a the remote interfaces that a remote ob3ect imp ements <see 5igure ,.+=. &he s#e$eton is a server side prox! for the remote ob3ect. It is much ike the stub c ass but resides on the server. &he ske eton is responsib e for ca ing the actua remote ob3ect imp ementation <see 5igure ,.+=. Figure %.%

*ootstrap Name 'erver &he 91I registr! is a simp e name server provided for storing references to remote ob3ects. &he server is responsib e for registering remote ob3ects with the registr! service . &he registr! keeps track of the addresses of remote ob3ects. A remote ob3ects hand e can be stored using the methods of 3ava.rmi.%aming c ass. A c ient can obtain a reference to a remote ob3ect b! ooking up in the server<s= registr! or as a resu t of a remote method ca . &he registr! server is necessar! on ! when making an initia contact with the app ication. An app ication can a so run its own registr! service. &he 91I registr! app ication <rmiregistry= is inc uded in A*P.

*ept. of CS#$ AI&$ 'anga ore

::

,-++)+,

Advances in OS Lab Programs Figure %.&

!-I )ayers 91I s!stem is organized as a four) a!er mode . #ach a!er performs some specific functions ike estab ishing the connection$ marsha ing of parameters$ etc. #ach a!er insu ates the a!ers above it from some detai s. &he four a!ers are. App ication a!er Prox! a!er 9emote reference a!er &ransport a!er

(pplication layer *ept. of CS#$ AI&$ 'anga ore :; ,-++)+,

Advances in OS Lab Programs &he app ication a!er is the actua imp ementation of the c ient and server app ication. 7ere$ the high eve ca s are made to access and export remote ob3ects. &he c ass 3ava.rmi."nicast9emoteOb3ect provides support for creating and exporting remote ob3ects. Ob3ects that re(uire remote behavior shou d extend "nicast9emoteOb3ect$ or if the ob3ect extends an! other c ass then the ob3ect must be exported exp icit ! b! ca ing the "nicast9emoteOb3ect<s= exportOb3ect<= methods. &he server creates remote ob3ects and registers them with the registr! service. A c ient gets a reference to a remote ob3ect b! ooking up in the serverQs registr!. After an initia contact with the server$ references to remote ob3ects can be obtained as a return va ue in a method ca . %roxy )ayer &o understand how 91I works$ we must understand the ro e of stubs R ske etons. A stub acts as a c ient<s= oca representative for remote ob3ect. &he c ient invokes a method on the oca stub. &he stub is responsib e for ca ing the method on the remote ob3ect. !esponsibilities of stub are,

It connects to the remote AB1. It seria izes an! arguments to a remote method. It reads the va ues returned b! a remote method. It returns the va ue to the c ient.

&he ske eton acts as a server side prox! of the remote ob3ects. !esponsibilities of s7eleton are,

It reads the parameters for the remote ob3ect. It ocates the ob3ect to be ca ed. It invokes the desired method on remote ob3ect. It transmits the resu t to the stub.

!emote !eference )ayer &he 9emote 9eference La!er is between the &ransport a!er and the Prox! a!er. It supports communication between the Stub and Ske eton. It is responsib e for passing the stream)oriented data received from the &ransport a!er to the Prox! a!er and vice versa. ransport )ayer

*ept. of CS#$ AI&$ 'anga ore

:>

,-++)+,

Advances in OS Lab Programs &his a!er is responsib e for setting and managing connections to remote machines. It sends to$ and receives data from$ other machines. 2hen the transport a!er receives a re(uest from the c ient)side 9emote 9eference La!er$ it estab ishes a socket connection to the server. If a significant amount of time passes with no activit! on the connection$ the transport a!er is responsib e for shutting down the connection. Distributed and Non3distributed models A ca to a remote ob3ect using 91I is simi ar to a ca to a oca ob3ect but there are a so some differences. )et<s= first see the similarities.

A reference to a remote ob3ect can be passed as an argument to a method or can be returned as a resu t b! a method. A remote ob3ect can be cast using the Aava s!ntax for casting. instanceo" operator can be used on remote ob3ects.

he :ava distributed ob>ect model differs from :ava ob>ect model in the following ways,

A c ient of a remote ob3ect a wa!s interacts with the remote interface$ not with the imp ementing c ass. A non)remote ob3ect passed as a parameter to a remote method is passed b! va ue. In contrar! to this$ a remote ob3ect is passed b! reference. &he e(ua s<=$ hashcode<= and toString<= methods defined in 3ava. ang.Ob3ect are overridden b! 3ava.rmi.server.9emoteOb3ect. 5or examp e$ the hashcode<= method returns the same hash code$ if two remote ob3ect stubs refer to the same remote ob3ect. &he toString<= method returns a string representation of the remote ob3ect. It inc udes information about the port number$ host name$ etc. &he e(ua s<Ob3ect ob3= method indicates whether some other ob3ect is Ie(ua toI this one.

An ob3ect$ passed as an argument to$ or returned b! a remote method must be seria izab e. ( remote ob>ect may be exported in two ways, A remote ob3ect must imp ement at east one interface that extends the 3ava.rmi.9emote interface. A server registers an! remote ob3ects with the rmiregistry. A c ient can obtain a reference to a remote ob3ect b! ooking up in the server<s= registr! or as a resu t of a remote method ca

!-I (%I

*ept. of CS#$ AI&$ 'anga ore

:?

,-++)+,

Advances in OS Lab Programs

Data ;low Diagram,

*ept. of CS#$ AI&$ 'anga ore

:@

,-++)+,