concurrency additional part of lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... ·...

16
CHAPTER 5 1 Fall 2010 - DE5 Concurrency Concurrency Concurrency Concurrency Additional Part of Additional Part of Lessen 4 Lessen 4 Dr. D. M. Akbar Hussain Department of Electronic Systems DE5 1 A classical problem similar to a real operating system for the access of different resources. Problem definition: Barber Shop Problem Barber Shop Problem Three chairs. Three barbers. Waiting area having capacity for four seats and additional space for customers to stand a and wait. Fire code limits the total number of customers (seating +standing). Customer cannot enter if pack to capacity. When a barber is free, customer waiting longest on the sofa can be served. If there are any standing customer he can now occupy the seat on the sofa Dr. D. M. Akbar Hussain Department of Electronic Systems DE5 2 If there are any standing customer, he can now occupy the seat on the sofa. Once a barber finished haircut, any barber can take the payment. As there is only one cash register, so payment from one customer is accepted at a time. Barber(s) time is divided into haircut, accepting payment and waiting for customers (sleeping).

Upload: others

Post on 26-May-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

1Fall 2010 - DE5

ConcurrencyConcurrencyConcurrencyConcurrencyAdditional Part of Additional Part of

Lessen 4Lessen 4

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 1

A classical problem similar to a real operating system for the access of different resources.

Problem definition:

Barber Shop ProblemBarber Shop Problem

Three chairs.

Three barbers.

Waiting area having capacity for four seats and additional space for customers to stand a and wait.

Fire code limits the total number of customers (seating +standing).

Customer cannot enter if pack to capacity.

When a barber is free, customer waiting longest on the sofa can be served.

If there are any standing customer he can now occupy the seat on the sofa

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 2

If there are any standing customer, he can now occupy the seat on the sofa.

Once a barber finished haircut, any barber can take the payment.

As there is only one cash register, so payment from one customer is accepted at a time.

Barber(s) time is divided into haircut, accepting payment and waiting for customers (sleeping).

Page 2: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

2Fall 2010 - DE5

Semaphore wait Signal

max_capacity Customer waits for room to enter shop Exiting customer signals to the waiting customer for entry

sofa Customer wait for seat on sofa Customer leaving sofa signals to waiting

Semaphore UsedSemaphore Used

sofa Customer wait for seat on sofa Customer leaving sofa signals to waiting standing customers

barber_chair Customer wait for empty barber chair Barber signals when his chair is empty

cust_read Barber waits until a customer is in chair Customer signals that he is in the b chair

finished Customer waits until his haircut finished Barber signals once he finished haircut

leave_b_chair Barber waits until customer gets up Customer signals barber when he gets up

payment Cashier waits for a customer to pay Customer signals cashier that he has paid

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 3

receipt Customer waits for a receipt for payment Cashier signals the acceptance of payment

coord Wait for a barber resource to be free to perform either haircut or cashiering function

Signal that a barber resource is free

Semaphore max_capacity = 20, sofa = 4, barber_chair = 3, coord = 3;Semaphore cust_ready= 0, finished = 0, leave_b_chair = 0, payment = 0, receipt = 0;

void customer ( ){

wait (max_capacity);enter_shop ( );

void barber ( ){

while (true){

void cashier ( ){

while (true){

Unfair BarberUnfair Barber

wait (sofa);sit_on_sofa ( );wait (barber_chair);get_up_from_sofa();signal (sofa);sit_in_barber_chair();signal (cust_ready);wait (finished);leave_barber_chair ();signal (leave_b_chair);pay( );signal (payment);

ait ( i t)

wait (cust_ready);wait (coord);cut_hair( );signal (coord);signal (finished);wait (leave_b_chair);signal (barber_chair);

}}

wait (payment);wait (coord);accept_pay( );signal (coord);signal (receipt);

}}

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 4

wait (receipt);exit_shop( );signal (max_capaity);

}

void main ( ){

customer( );barber ( );cashier( );

}

Page 3: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

3Fall 2010 - DE5

Things can be improved interms of timing by using some more semaphore as;int count; Semaphore mutex1 = 1, mutex2 = 1; Semaphore max_capacity = 20, sofa = 4, barber_chair = 3, coord = 3;Semaphore cust_ready= 0, finished = 0, leave_b_chair = 0, payment = 0, receipt = 0;

void customer ( ){

int custnr;

void barber ( ){

int b cust;

void cashier ( ){

while (true)

Fair BarberFair Barber

;wait (max_capacity);enter_shop ( );wait (mutex1);count = count + 1; custnr = count;signal (mutex1);wait (sofa);sit_on_sofa ( );wait (barber_chair);get_up_from_sofa();signal (sofa);sit_in_barber_chair();wait (mutex2);enqueue1(custnr);signal (cust ready);

int b_cust;while (true){

wait (cust_ready);wait (mutex2);dequeue1 (b_cust);signal (mutex2);wait (coord);Cut_hair( );signal (coord);signal (finished[custnr]);wait (leave_b_chair);signal (barber_chair);

while (true){

wait (payment);wait (coord);accept_pay( );signal (coord);signal (receipt);

}}

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 5

signal (cust_ready);signal (mutex2);wait (finished[custnr]);leave_barber_chair ();signal (leave_b_chair);pay( );signal (payment);wait (receipt);exit_shop( );signal (max_capaity);

}

}}

Semaphores exhibitexhibit flexibleflexible andand powerfulpowerful mechanismmechanism for enforcingmutual exclusion But potentially it can produce incorrect program

MonitorsMonitors

mutual exclusion. But potentially it can produce incorrect programbecausebecause ofof thethe scatteringscattering ofof thethe operationoperation.

Monitors are another option which is basically a programmingprogramming languagelanguageconstructconstruct providing equivalent functionality to the semaphores but easierto implement and control.

A monitor is a softwaresoftware modulemodule consists of one or more functions(initializing sequence and the local data).

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 6

Page 4: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

4Fall 2010 - DE5

Characteristics of a Monitor with Signal

Local data is only accessible to monitor’smonitor’s functionsfunctions..

MonitorsMonitors

A process can enter into monitor byby callingcalling one of its function.

OnlyOnly oneone processprocess isis allowedallowed toto executeexecute inin monitormonitor atat anyany givengiven timetime, anyother process that may have invoked the monitor remains suspended till itbecomes available. ItIt isis basicallybasically thisthis characteristicscharacteristics whichwhich makesmakes mutualmutualexclusionexclusion possiblepossible..

Because of the previous condition data variables in the monitor will also beaccessibleaccessible byby onlyonly oneone processprocess atat aa timetime, therefore, shared variables can beprotected by placing them in the monitor.

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 7

p y p g

Synchronization is also provided in the monitor for concurrent processing throughcwait (c) and csignal (c) operations.

Queue for Entering

condition c1

Monitor waiting area Monitor

Monitor StructureMonitor Structure

Condition VariablesCondition Variables

Local DataLocal Data

Function ()Function ()

Function ()Function ()

cwait (c1)

condition cn

cwait (cn)

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 8

Initialization CodeInitialization Code

csignal(ci )

urgent queue

Exit

Page 5: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

5Fall 2010 - DE5

char buffer [n]; int nextin, nextout; int count; int notfull, notempty;nextin = 0; nextout = 0; count = 0;

void append (char x){

void take (char x)

Producer Consumer Solution with Producer Consumer Solution with MonitorMonitor

{if (count ==n)

cwait (notfull);buffer[nextin] = x;nextin = (nextin + 1) % n;count ++;csignal (notempty);

}

void producer ( )char x;

{if (count == 0)

cwait (notempty);x = buffer[nextout];nextout = (nextout + 1)%n;count --;csignal (notfull);

}

void consumer ( )char x;

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 9

;{

while (true){

produce (x);append (x);

}}

char x;{

while (true){

take (x);consume (x);

}}

In the original version it requires that if there is at least one process in the conditionqueue, a process from that queue runs immediately when another process issues acsignal for that condition. Therefore, csignal issuing process either immediately exitmonitor or be suspended in the monitor.There are two limitations with this approach:

Modified MonitorModified Monitor

There are two limitations with this approach:if csignal issuing process has not finished with the monitor, two additional process context switches are need (one to suspend, another to resume).A perfect reliable process scheduling is a must condition. For example, when a process issue csignal a process from the condition queue must be activated before any chance of scheduler allowing a process to enter into the monitor.

Improved development uses cnotify primitive instead of csignal, meaning that when aprocess issues a cnotify (x), it tells the x condition queue and continue executing. Thebenefit of notifying the condition queue is that process residing at the front of queue willresume at some convenient time when monitor is available. On the other hand it is not

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 10

guarantee that another process will not enter in the monitor before the waiting process.For that instead of ”if” statement, a ”while” statement is used, which ensures the aboveconstraint to be solved. It is just one extra evaluation of the condition but it saves twoprocess switches and no constraints on when a process must run after a notify.The improved version is less prone to errors and also it looked more modular approach toprogram construction.(HOARE & LAMPSON/REDELL)

Page 6: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

6Fall 2010 - DE5

void append (char x){

while (count ==n) /* instead of if statement */i ( f ll)

Modified Monitor CodeModified Monitor Code

cwait (notfull);buffer[nextin] = x;nextin = (nextin + 1) % n;count ++;cnotify (notempty);

}

void take (char x){

while (count == 0) /* instead of if statement */cwait (notempty);

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 11

cwa t ( ote pty);x = buffer[nextout];nextout = (nextout + 1)%n;count --;cnotify (notfull);

}

For any two processes to interact, it is essential to have synchronization and essential to have synchronization and communication.communication.

1. Synchronization is for Mutual Exclusion2. Communication is for exchange of information

Message PassingMessage Passing

SynchronizationSynchronizationCommunicationCommunication

“Message Passing” can provide both“Message Passing” can provide both

Added advantage; it works for distributed systems, multi-processors shared memory systems and uni-processors.

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 12

y pComes in many flavors.Comes in many flavors.

Essentially has this minimum set of operations:send (destination, message)

receive (source, message)

Page 7: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

7Fall 2010 - DE5

SynchronizationSynchronization AddressingAddressing

Design Issues in Message PassingDesign Issues in Message Passing

ReceiveReceive SendSend

BlockingBlocking

Non BlockingNon BlockingBlockingBlocking

DirectDirect IndirectIndirect

ReceiveReceive

SendSend

StaticStatic

DynamicDynamic

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 13

Test for ArrivalTest for ArrivalNon BlockingNon Blocking

OwnershipOwnershipExplicitExplicit

ImplicitImplicit

FormatFormat

QueuingQueuing

Design Issues in Message PassingDesign Issues in Message Passing

ContentContent LengthLength

FixedFixed

Fairest of allFairest of all PriorityPriority

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 14

VariableVariable

Page 8: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

8Fall 2010 - DE5

Receiver cannot receive until a message is sent to him. Possible discipline for send & receive.

Blocking Blocking sendsend -- Blocking Blocking receivereceive

SynchronizationSynchronization

BothBoth sendersender andand receiverreceiver isis blockedblocked until message isdelivered, this is tighttight synchronizationsynchronization schemescheme and calledrendezvousrendezvous..

Non Blocking Non Blocking sendsend -- Blocking Blocking receivereceive

It is a useful combination havinghaving libertyliberty toto sendsend asas manymany

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 15

v gv g b yb y yymessagesmessages toto differentdifferent destinationsdestinations quicklyquickly, blocking receiveis useful too, as a server process waiting to provide any service toother processes.

SynchronizationSynchronization

Non Blocking Non Blocking sendsend -- Non Blocking Non Blocking receivereceive

NonNon blockingblocking sendsend isis thethe mostmost naturalnatural optionoption for many systems. Let usconsider the simplest example case of printing request it will be foolish toconsider the simplest example case of printing request, it will be foolish tokeep waiting till the printing job finished. The only concern could be in theevent of error generation of multiple messages which could lead to usesystem resources for no productivity.

From receive primitive, blockingblocking isis thethe naturalnatural optionoption because therequested information has to be received first before proceeding. However, ifthe message is lost or the sending process have problem to send therequested information, receiver will be blocked indefinitely.

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 16

So may be non blocking, but then one has to ensure that the messages arenot lost, may be it can check (test for arrival) for any waiting messages beforeresuming its processing.

Page 9: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

9Fall 2010 - DE5

DirectDirect AddressingAddressing

send primitive includes a specific identifier of the destination process.

Direct/Indirect AddressingDirect/Indirect Addressing

Receive can have two options:

Explicit receive: which must designate a sending process, the receivingprocess must know ahead of time that a message is expected (which maybe ok for cooperating processes). Otherwise, it is not possible toanticipate incoming process from different sources.

Implicit receive: In which case source parameter of the receive

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 17

p pprimitive contains a returned value once the receive operation isaccomplished.

MessagesMessages areare notnot directlydirectly sentsent toto receiverreceiver andand vicevice versaversa, instead they

Indirect AddressingIndirect Addressing

are sent to a sharedshared datadata structurestructure mademade ofof queuesqueues (mail(mail boxes)boxes) to holddata for some time. The sender and receiver is decoupled and hence providemore flexibility in the use of messages.

NumberNumber ofof optionsoptions:One to one (could be a private link between twotwo processesprocesses)One to many (broadcasting),(broadcasting),Many to one (client/server)(client/server)Many to many.

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 18

y y

Page 10: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

10Fall 2010 - DE5

The association of processes could be static or dynamic:

OO ld b i i

Indirect AddressingIndirect Addressing

1.1. OneOne toto oneone could be static version

2.2. ManyMany toto oneone could be dynamic by creating ports may be using connectand disconnect. Generally ports are created and owned by thereceiving process, so when the process is destroyed port also goes withit. For a general mail box, operating system can create mail box serviceand hence owned by the operating system and an explicit command willbe required to destroy this mail box.

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 19

Sending Processes

P1 PnQ1

Indirect AddressingIndirect Addressing

Mailbox Port

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 20

Receiving Processes

Q1 Qn P1 Pn

Sending Processes

Page 11: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

11Fall 2010 - DE5

Depends on the objective of the messaging facility and also configuration meaning single machine or distributed system.

Fixed length messages: Fixed length messages: Minimize processing and storage overhead.

Message FormatMessage Format

Fixed length messages: Fixed length messages: Minimize processing and storage overhead.Variable length messages:Variable length messages: Flexible.

Message has two parts, headerheaderwhich may contain a type fieldfor distinction among varioustype of contents, control informationfor example a pointer field to createlinked list of messages, a sequence of

Message TypeMessage Type

Destination IDDestination ID

Source IDSource IDMessage LengthMessage Length

Control InformationControl Information

HeaderHeader

Typical Message Typical Message FormatFormat

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 21

of numbers to keep record of the numberand order of the messages and also may bepriority field.

BodyBody is the actual message content.

Message ContentsMessage ContentsBodyBody

1. The simplest and the fairest approach could be FIFO,b i l itit illill tt kk ff it tiit ti h

QueuingQueuing

obviously, itit willwill notnot workwork forfor situationsituation when messageshave some urgent priority attached with them.

2. Message can have a prioritypriority fieldfield basedbased onon theirtheir typetype sothey will be dealt accordingly.

3. The receiver can inspect the message queue and can decide

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 22

whatwhat hehe isis lookinglooking forfor.

Page 12: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

12Fall 2010 - DE5

Mutual Exclusion with Message Mutual Exclusion with Message PassingPassing

1.1. Non Blocking Non Blocking send - Blocking receiveBlocking receiveconst int n /* number of processes */

id (i t i)2. Processes are sharing a mail box mutex3. Mail box is initialized with a single message

with NULL contents4. Process wishing to enter its critical section

first attempts to get a message5. If mail box is empty, message is blocked6. Once receiver has message, it can enter into the

critical section7 M f ti t k f

void p (int i){message msg;

while (true){receive (mutex, msg);critical section;send (mutex, msg);

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 23

7. Message function as a token for processes remainder}

}

void producer ( ){message pmsg;

while (true){

void consumer ( ){message cmsg;

while (true){

ProdProd--Cons Solution with Message Cons Solution with Message PassingPassing

{receive (mayproduce, pmsg);pmsg = produce ( );send (mayconsume, pmsg);}

}const int capacity = /* buffering */;int i;void main ( ){

{receive (mayconsume, cmsg);cmsg = consume ( );send (mayproduce, cmsg);}

}const int null = /* empty message */;

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 24

{create_mailbox (mayproduce);create_mailbox (mayconsume);for (int i= 1; i<=capacity; i++)

send (mayproduce, null);producer; consumer;}

Page 13: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

13Fall 2010 - DE5

What happens if more than one process performs one process performs receive operation concurrently:concurrently:

If mailbox has a message, it will be delivered to only one process, others will be blockedIf mailbox queue is empty, all will be blocked

DescriptionDescription

If mailbox queue is empty, all will be blockedGenerally this is true for all message passing facilities.

In the previous example, two mailboxes were created, producer send data to the mayconsume mailbox. It serves as a buffer, which is organized as a queue and as long as there is at least one message, consume can consume it. Initially, mayproduce is filled with a number of null messages equal to the capacity of the capacity variable. Number of messages shrinks with each production in mayproduce and grows with each consumption.

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 25

May May produceproduce

May May consumeconsume

Problem Definition:

Data (file, memory location or bank of registers) to be shared among processes

Couple of reader and writer processes are present with following

Reader Writer ProblemReader Writer Problem

Couple of reader and writer processes are present with following constraints:

No restriction on readers to read data

Only one writer can write at one time

During writing no reader is allowed to read

One must understand that no writer is allowed to read and no reader canwrite, this is a restricted case, if we consider the general case in which both areallowed to do these functions then any portion of the shared area can be

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 26

considered critical section. Therefore, a general mutual exclusion solution canbe employed. That solution is in general very slow, so here restricted case istypically very efficient. Consider for example a library catalog, ordinary usersread the catalog to locate a book and only the librarian can update or changethe data. So in the general case every access to the catalog will be considercritical section and only one user will be able to read the data. Which is Goingto be very slow indeed.

Page 14: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

14Fall 2010 - DE5

Reader has Priorityint readcount; semaphore x = 1; semaphore wsem = 1;void reader ( ){

while (true){

Writer has Priorityint readcount, writecount; semaphore x = 1, y = 1, z = 1; semaphore wsem = 1, rsem = 1;

void reader ( ){

while (true){

void writer ( ){

while (true){

Reader Writer with SemaphoresReader Writer with Semaphores

{wait (x);readcount ++;if (readcount == 1)

wait (wsem);signal (x);readunit ( );wait (x);readcount --;if (readcount == 0)

signal (wsem);signal (x);

}

{wait (z);wait (rsem);wait (x);readcount ++;if (readcount == 1)

wait (wsem);signal (x);signal (rsem);signal (z);readunit ( );wait (x);readcount --;

{wait (y);writecount ++;if (writecount == 1)

wait (rsem);signal (y);wait (wsem);writeunit ( );signal (wsem);wait (y);writecount --;if (writecount == 1)

wait (rsem);

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 27

}}void writer ( ){

while (true){

wait (wsem);writeunit ( );signal (wsem);

}}

if (readcount == 0)signal (wsem);

signal (x);}

}

signal (y);

}}

ReaderReader hashas prioritypriority1. In this case, writers can be starved as long as one reader is present.2. wsem is used to enforce mutual exclusion in the reader function.3. Only one writer is allowed to have access, during which no reading and writing by

DiscussionDiscussion

others.4. When there is no reader, the first one wants to read has to wait on wsem, the

subsequent readers don’t have to wait.5. readcount is used to keep track of number of readers.6. semaphore x is used to assure that readcount is updated properly.

WriterWriter hashas prioritypriority1. The modified version, which guarantee that no reader can access the data once a writer

has shown the desire to access, obviously, few more semaphores and variables are

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 28

required.2. semaphore rsem is used to inhibit readers once a writer wishes to access.3. writecount is used to control the setting of rsem.

4. semaphore y is used to assure that writecount is updated properly.5. Only one reader is allowed to queue on rsem all other will queue on z, because writer

will not be able to jump all of them.

Page 15: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

15Fall 2010 - DE5

Readers only in the system 1. wsem set2. no queue

Writers only in the system 1. wsem and rsem set

State of QueuesState of Queues

2. writers queue on wsemBoth readers and writers with read first 1. wsem set by reader

2. rsem is set by writer3. all writers queue on wsem4. one reader queue on rsem5. all other readers queue on z

Both readers and writers with write first 1. wsem set by writer2 i t b d

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 29

2. rsem is set by reader3. all writers queue on wsem4. one reader queue on rsem5. all other readers queue on z

void reader (int i){

message rmsg;while (true){

rmsg = i;send (readrequest, rmsg);

void controller ( ){

while (true){

if (count > 0){

if (!empty (finished)){receive (finished msg);

Reader Writer with Message PassingReader Writer with Message Passing

( q , g);receive (mbox[i], rmsg);readunit ( );rmsg = i;send (finished, rmsg);

}}void writer (int i){

message rmsg;while (true){

rmsg = i;d ( it t )

receive (finished, msg);count ++;}

else if (!empty (writerequest)){receive (writerequest, msg);write_id = msg.id;count = count - 100;}

else if (!empty (readrequest)){receive (readrequest, msg);count --;send (msg.id, “ok”);}

}

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 30

send (writerequest, rmsg);writeunit ( );rmsg = i;send (finished, rmsg);

}}

if (count == 0){send (write_id, “ok”);receive (finished, msg);count = 100;}

while (count < 0){receive (finished, msg);count ++;}

}

Page 16: Concurrency Additional Part of Lessen 4homes.et.aau.dk/akh/2011/operatingsystem-11_files/... · resume at some convenient time when monitor is available. On the other hand it is not

CHAPTER 5

16Fall 2010 - DE5

1. The controller process actually access the shared data.

2. Any process wishing to access the shared data send request to controller.

3. “OK” indicates access granted and finished message indicates completion.

DiscussionDiscussion

4. Controller has three mailboxes for each type of messages.

5. Controller process gives priority to the write process request messages.

6. Mutual exclusion is forced through count variable, which is initialized to 100 here, indicating maximum number of readers allowed.

i. If count > 0, indicates no writer is waitingno writer is waiting, there may or may not be any reader.

ii. If count = 0, only write request is outstandingonly write request is outstanding, so allowed till fi i h d

Dr. D. M. Akbar Hussain

Department of Electronic SystemsDE5 31

finished message.

iii. If count < 0, indicates a writer has launched a requestindicates a writer has launched a request, and waiting to clear all active readers.

So only finished messages are serviced